Source Code
Overview
ETH Balance
0 ETH
ETH Value
$0.00View more zero value Internal Transactions in Advanced View mode
Advanced mode:
Cross-Chain Transactions
Loading...
Loading
This contract contains unverified libraries: PositionManagement, TickLibrary
This contract may be a proxy contract. Click on More Options and select Is this a proxy? to confirm and enable the "Read as Proxy" & "Write as Proxy" tabs.
Contract Name:
LimitOrderLens
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.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.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: MIT
pragma solidity ^0.8.0;
import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";
using PoolIdLibrary for PoolKey global;
/// @notice Returns the key for identifying a pool
struct PoolKey {
/// @notice The lower currency of the pool, sorted numerically
Currency currency0;
/// @notice The higher currency of the pool, sorted numerically
Currency currency1;
/// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
uint24 fee;
/// @notice Ticks that involve positions must be a multiple of tick spacing
int24 tickSpacing;
/// @notice The hooks of the pool
IHooks hooks;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "./PoolKey.sol";
type PoolId is bytes32;
/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
/// @notice Returns value equal to keccak256(abi.encode(poolKey))
function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
assembly ("memory-safe") {
// 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
poolId := keccak256(poolKey, 0xa0)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {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 {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 {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
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: 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: UNLICENSED
pragma solidity ^0.8.20;
import "../../src/libraries/FullMath.sol";
import "../../src/libraries/FixedPoint96.sol";
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x, "liquidity overflow");
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount0)
internal
pure
returns (uint128 liquidity)
{
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
uint256 intermediate = FullMath.mulDiv(sqrtPriceAX96, sqrtPriceBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtPriceBX96 - sqrtPriceAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount1)
internal
pure
returns (uint128 liquidity)
{
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtPriceBX96 - sqrtPriceAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtPriceX96 A sqrt price representing the current pool prices
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtPriceX96,
uint160 sqrtPriceAX96,
uint160 sqrtPriceBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
if (sqrtPriceX96 <= sqrtPriceAX96) {
liquidity = getLiquidityForAmount0(sqrtPriceAX96, sqrtPriceBX96, amount0);
} else if (sqrtPriceX96 < sqrtPriceBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtPriceX96, sqrtPriceBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity)
internal
pure
returns (uint256 amount0)
{
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
return FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtPriceBX96 - sqrtPriceAX96, sqrtPriceBX96
) / sqrtPriceAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity)
internal
pure
returns (uint256 amount1)
{
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
return FullMath.mulDiv(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtPriceX96 A sqrt price representing the current pool prices
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtPriceX96,
uint160 sqrtPriceAX96,
uint160 sqrtPriceBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
if (sqrtPriceX96 <= sqrtPriceAX96) {
amount0 = getAmount0ForLiquidity(sqrtPriceAX96, sqrtPriceBX96, liquidity);
} else if (sqrtPriceX96 < sqrtPriceBX96) {
amount0 = getAmount0ForLiquidity(sqrtPriceX96, sqrtPriceBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtPriceAX96, sqrtPriceX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtPriceAX96, sqrtPriceBX96, liquidity);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.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
// 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 {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: 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 {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 {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 {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.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) (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
// 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
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) (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.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 {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 {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;
/// @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: 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
pragma solidity ^0.8.0;
/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
/// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol)
library BitMath {
/// @notice Returns the index of the most significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the most significant bit, must be greater than 0
/// @return r the index of the most significant bit
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020500060203020504000106050205030304010505030400000000))
}
}
/// @notice Returns the index of the least significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the least significant bit, must be greater than 0
/// @return r the index of the least significant bit
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
// Isolate the least significant bit.
x := and(x, sub(0, x))
// For the upper 3 bits of the result, use a De Bruijn-like lookup.
// Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
// forgefmt: disable-next-item
r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
0x8040405543005266443200005020610674053026020000107506200176117077)))
// For the lower 5 bits of the result, use a De Bruijn lookup.
// forgefmt: disable-next-item
r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @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;
/// @notice Interface for functions to access any storage slot in a contract
interface IExtsload {
/// @notice Called by external contracts to access granular pool state
/// @param slot Key of slot to sload
/// @return value The value of the slot as bytes32
function extsload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access granular pool state
/// @param startSlot Key of slot to start sloading from
/// @param nSlots Number of slots to load into return value
/// @return values List of loaded values.
function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);
/// @notice Called by external contracts to access sparse pool state
/// @param slots List of slots to SLOAD from.
/// @return values List of loaded values.
function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @notice Interface for functions to access any transient storage slot in a contract
interface IExttload {
/// @notice Called by external contracts to access transient storage of the contract
/// @param slot Key of slot to tload
/// @return value The value of the slot as bytes32
function exttload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access sparse transient pool state
/// @param slots List of slots to tload
/// @return values List of loaded values
function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
/// @notice Parameter struct for `ModifyLiquidity` pool operations
struct ModifyLiquidityParams {
// the lower and upper tick of the position
int24 tickLower;
int24 tickUpper;
// how to modify the liquidity
int256 liquidityDelta;
// a value to set if you want unique liquidity positions at the same range
bytes32 salt;
}
/// @notice Parameter struct for `Swap` pool operations
struct SwapParams {
/// Whether to swap token0 for token1 or vice versa
bool zeroForOne;
/// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
int256 amountSpecified;
/// The sqrt price at which, if reached, the swap will stop executing
uint160 sqrtPriceLimitX96;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title 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: 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
// 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
// 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: 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: BUSL-1.1
pragma solidity ^0.8.20;
import {Currency} from "v4-core/types/Currency.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
/// @notice Library used to interact with PoolManager.sol to settle any open deltas.
/// @dev Note that sync() is called before any erc-20 transfer in `settle`.
library CurrencySettler {
using SafeERC20 for IERC20;
/// @notice Settle (pay) a currency to the PoolManager
/// @param currency Currency to settle
/// @param manager IPoolManager to settle to
/// @param payer Address of the payer, the token sender
/// @param amount Amount to send
/// @param burn If true, burn the ERC-6909 token, otherwise ERC20-transfer to the PoolManager
function settle(Currency currency, IPoolManager manager, address payer, uint256 amount, bool burn) internal {
if (burn) {
manager.burn(payer, currency.toId(), amount);
} else if (currency.isAddressZero()) {
manager.settle{value: amount}();
} else {
manager.sync(currency);
if (payer != address(this)) {
IERC20(Currency.unwrap(currency)).safeTransferFrom(payer, address(manager), amount);
} else {
IERC20(Currency.unwrap(currency)).safeTransfer(address(manager), amount);
}
manager.settle();
}
}
/// @notice Take (receive) a currency from the PoolManager
/// @param currency Currency to take
/// @param manager IPoolManager to take from
/// @param recipient Address of the recipient, the token receiver
/// @param amount Amount to receive
/// @param claims If true, mint the ERC-6909 token, otherwise ERC20-transfer from the PoolManager to recipient
function take(Currency currency, IPoolManager manager, address recipient, uint256 amount, bool claims) internal {
claims ? manager.mint(recipient, currency.toId(), amount) : manager.take(currency, recipient, amount);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {Currency} from "../types/Currency.sol";
import {CurrencyReserves} from "./CurrencyReserves.sol";
import {NonzeroDeltaCount} from "./NonzeroDeltaCount.sol";
import {Lock} from "./Lock.sol";
/// @notice A helper library to provide state getters that use exttload
library TransientStateLibrary {
/// @notice returns the reserves for the synced currency
/// @param manager The pool manager contract.
/// @return uint256 The reserves of the currency.
/// @dev returns 0 if the reserves are not synced or value is 0.
/// Checks the synced currency to only return valid reserve values (after a sync and before a settle).
function getSyncedReserves(IPoolManager manager) internal view returns (uint256) {
if (getSyncedCurrency(manager).isAddressZero()) return 0;
return uint256(manager.exttload(CurrencyReserves.RESERVES_OF_SLOT));
}
function getSyncedCurrency(IPoolManager manager) internal view returns (Currency) {
return Currency.wrap(address(uint160(uint256(manager.exttload(CurrencyReserves.CURRENCY_SLOT)))));
}
/// @notice Returns the number of nonzero deltas open on the PoolManager that must be zeroed out before the contract is locked
function getNonzeroDeltaCount(IPoolManager manager) internal view returns (uint256) {
return uint256(manager.exttload(NonzeroDeltaCount.NONZERO_DELTA_COUNT_SLOT));
}
/// @notice Get the current delta for a caller in the given currency
/// @param target The credited account address
/// @param currency The currency for which to lookup the delta
function currencyDelta(IPoolManager manager, address target, Currency currency) internal view returns (int256) {
bytes32 key;
assembly ("memory-safe") {
mstore(0, and(target, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(32, and(currency, 0xffffffffffffffffffffffffffffffffffffffff))
key := keccak256(0, 64)
}
return int256(uint256(manager.exttload(key)));
}
/// @notice Returns whether the contract is unlocked or not
function isUnlocked(IPoolManager manager) internal view returns (bool) {
return manager.exttload(Lock.IS_UNLOCKED_SLOT) != 0x0;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// 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;
/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Math library for liquidity
library LiquidityMath {
/// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
/// @param x The liquidity before change
/// @param y The delta by which liquidity should be changed
/// @return z The liquidity delta
function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {
assembly ("memory-safe") {
z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y))
if shr(128, z) {
// revert SafeCastOverflow()
mstore(0, 0x93dafdf1)
revert(0x1c, 0x04)
}
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.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: 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
// 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.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: 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: 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 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)
}
}
}// 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))
}
}
}{
"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,
"libraries": {
"src/Unilaunch/LimitOrderBook/periphery/LimitOrderLens.sol": {
"PositionManagement": "0x8352fcca6655379bdf3dd7547298ed46997a5ce6",
"TickLibrary": "0xc34372e663a5bd02e68a2d0e4908ad90540ae33c",
"LimitOrderLensTickLogic": "0x64e9052dcf51486bf104715ceea830d779c51ca3"
}
}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"uint256","name":"totalOrders","type":"uint256"},{"internalType":"uint256","name":"minOrders","type":"uint256"}],"name":"InsufficientOrders","type":"error"},{"inputs":[],"name":"InvalidScaleParameters","type":"error"},{"inputs":[{"internalType":"uint256","name":"totalOrders","type":"uint256"},{"internalType":"uint256","name":"maxOrderLimit","type":"uint256"}],"name":"OrderLimitExceeded","type":"error"},{"inputs":[],"name":"TickRangeTooSmall","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"previousAdmin","type":"address"},{"indexed":false,"internalType":"address","name":"newAdmin","type":"address"}],"name":"AdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"beacon","type":"address"}],"name":"BeaconUpgraded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"FACTORY_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MIN_ORDERS","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ZERO_DELTA","outputs":[{"internalType":"BalanceDelta","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"poolId","type":"bytes32"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"}],"name":"addPoolId","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"totalAmount","type":"uint256"},{"internalType":"uint256","name":"totalOrders","type":"uint256"},{"internalType":"uint256","name":"sizeSkew","type":"uint256"}],"name":"calculateOrderSizes","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"bytes32","name":"positionKey","type":"bytes32"}],"name":"decodePositionKey","outputs":[{"internalType":"int24","name":"bottomTick","type":"int24"},{"internalType":"int24","name":"topTick","type":"int24"},{"internalType":"bool","name":"isToken0","type":"bool"},{"internalType":"uint256","name":"nonce","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"getAllPools","outputs":[{"components":[{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"poolKey","type":"tuple"},{"internalType":"string","name":"token0Symbol","type":"string"},{"internalType":"string","name":"token1Symbol","type":"string"}],"internalType":"struct PoolStruct[]","name":"pools","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"PoolId","name":"poolId","type":"bytes32"}],"name":"getAllUserPositionsForPool","outputs":[{"components":[{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"BalanceDelta","name":"fees","type":"int256"},{"internalType":"bytes32","name":"positionKey","type":"bytes32"}],"internalType":"struct ILimitOrderManager.PositionInfo[]","name":"positions","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"PoolId","name":"poolId","type":"bytes32"},{"internalType":"uint256","name":"offset","type":"uint256"},{"internalType":"uint256","name":"limit","type":"uint256"}],"name":"getCancellablePositions","outputs":[{"internalType":"bytes32[]","name":"positionKeys","type":"bytes32[]"},{"internalType":"uint256","name":"count","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"PoolId","name":"poolId","type":"bytes32"},{"internalType":"uint256","name":"offset","type":"uint256"},{"internalType":"uint256","name":"limit","type":"uint256"}],"name":"getClaimablePositions","outputs":[{"internalType":"bytes32[]","name":"positionKeys","type":"bytes32[]"},{"internalType":"uint256","name":"count","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"poolId","type":"bytes32"},{"internalType":"bool","name":"isToken0","type":"bool"}],"name":"getMinAndMaxTickForLimitOrders","outputs":[{"internalType":"int24","name":"minTick","type":"int24"},{"internalType":"int24","name":"maxTick","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"poolId","type":"bytes32"},{"internalType":"bool","name":"isToken0","type":"bool"}],"name":"getMinAndMaxTickForScaleOrders","outputs":[{"internalType":"int24","name":"minTick","type":"int24"},{"internalType":"int24","name":"maxTick","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"}],"name":"getPoolId","outputs":[{"internalType":"PoolId","name":"","type":"bytes32"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"PoolId","name":"poolId","type":"bytes32"},{"internalType":"bytes32","name":"positionKey","type":"bytes32"}],"name":"getPositionBalances","outputs":[{"components":[{"internalType":"uint256","name":"principal0","type":"uint256"},{"internalType":"uint256","name":"principal1","type":"uint256"},{"internalType":"uint256","name":"fees0","type":"uint256"},{"internalType":"uint256","name":"fees1","type":"uint256"}],"internalType":"struct ILimitOrderManager.PositionBalances","name":"balances","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"poolId","type":"bytes32"},{"internalType":"uint24","name":"numTicks","type":"uint24"}],"name":"getTickInfosAroundCurrent","outputs":[{"internalType":"int24","name":"currentTick","type":"int24"},{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"components":[{"internalType":"int24","name":"tick","type":"int24"},{"internalType":"uint160","name":"sqrtPrice","type":"uint160"},{"internalType":"uint256","name":"token0Amount","type":"uint256"},{"internalType":"uint256","name":"token1Amount","type":"uint256"},{"internalType":"uint256","name":"totalTokenAmountsinToken1","type":"uint256"}],"internalType":"struct TickInfo[]","name":"tickInfos","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"getUserPositionCountsAcrossPools","outputs":[{"components":[{"internalType":"PoolId","name":"poolId","type":"bytes32"},{"internalType":"uint256","name":"count","type":"uint256"}],"internalType":"struct LimitOrderLens.PoolPositionCount[]","name":"counts","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"offset","type":"uint256"},{"internalType":"uint256","name":"limit","type":"uint256"}],"name":"getUserPositionsPaginated","outputs":[{"components":[{"internalType":"PoolId","name":"poolId","type":"bytes32"},{"internalType":"bytes32","name":"positionKey","type":"bytes32"},{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"string","name":"token0Symbol","type":"string"},{"internalType":"string","name":"token1Symbol","type":"string"},{"internalType":"uint8","name":"token0Decimals","type":"uint8"},{"internalType":"uint8","name":"token1Decimals","type":"uint8"},{"internalType":"bool","name":"isToken0","type":"bool"},{"internalType":"int24","name":"bottomTick","type":"int24"},{"internalType":"int24","name":"topTick","type":"int24"},{"internalType":"int24","name":"currentTick","type":"int24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"uint160","name":"sqrtPrice","type":"uint160"},{"internalType":"uint160","name":"sqrtPriceBottomTick","type":"uint160"},{"internalType":"uint160","name":"sqrtPriceTopTick","type":"uint160"},{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"uint256","name":"positionToken0Principal","type":"uint256"},{"internalType":"uint256","name":"positionToken1Principal","type":"uint256"},{"internalType":"uint256","name":"positionFeeRevenue0","type":"uint256"},{"internalType":"uint256","name":"positionFeeRevenue1","type":"uint256"},{"internalType":"uint256","name":"totalCurrentToken0Principal","type":"uint256"},{"internalType":"uint256","name":"totalCurrentToken1Principal","type":"uint256"},{"internalType":"uint256","name":"feeRevenue0","type":"uint256"},{"internalType":"uint256","name":"feeRevenue1","type":"uint256"},{"internalType":"uint256","name":"totalToken0AtExecution","type":"uint256"},{"internalType":"uint256","name":"totalToken1AtExecution","type":"uint256"},{"internalType":"uint256","name":"orderSize","type":"uint256"},{"internalType":"bool","name":"claimable","type":"bool"}],"internalType":"struct DetailedUserPosition[]","name":"positions","type":"tuple[]"},{"internalType":"uint256","name":"totalCount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_limitOrderManagerAddr","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"limitOrderManager","outputs":[{"internalType":"contract LimitOrderManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"poolId","type":"bytes32"},{"internalType":"int24","name":"bottomTick","type":"int24"},{"internalType":"int24","name":"topTick","type":"int24"}],"name":"minAndMaxScaleOrders","outputs":[{"internalType":"uint256","name":"minOrders","type":"uint256"},{"internalType":"uint256","name":"maxOrders","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"","type":"bytes32"}],"name":"poolIdToKey","outputs":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"poolManager","outputs":[{"internalType":"contract IPoolManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"proxiableUUID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"poolId","type":"bytes32"}],"name":"removePoolId","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"}],"name":"upgradeTo","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"PoolId","name":"poolId","type":"bytes32"},{"internalType":"bool","name":"isToken0","type":"bool"},{"internalType":"int24","name":"bottomTick","type":"int24"},{"internalType":"int24","name":"topTick","type":"int24"},{"internalType":"uint256","name":"totalAmount","type":"uint256"},{"internalType":"uint256","name":"totalOrders","type":"uint256"},{"internalType":"uint256","name":"sizeSkew","type":"uint256"}],"name":"verifyOrderSizes","outputs":[{"components":[{"internalType":"int24","name":"lowerTick","type":"int24"},{"internalType":"int24","name":"upperTick","type":"int24"},{"internalType":"uint256","name":"amount","type":"uint256"}],"internalType":"struct OrderStruct[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"}]Contract Creation Code
60a060405230608052348015610013575f80fd5b5061001c610021565b6100dd565b5f54610100900460ff161561008c5760405162461bcd60e51b815260206004820152602760248201527f496e697469616c697a61626c653a20636f6e747261637420697320696e697469604482015266616c697a696e6760c81b606482015260840160405180910390fd5b5f5460ff908116146100db575f805460ff191660ff9081179091556040519081527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b565b608051615f566101115f395f8181610aa701528181610b2c01528181610f4301528181610fc801526110ad0152615f565ff3fe60806040526004361061025d575f3560e01c80638da5cb5b1161014b578063b2405a37116100c6578063d88ff1f41161007c578063eb33b75011610062578063eb33b7501461082e578063f2fde38b1461085b578063ffa2505b1461087a575f80fd5b8063d88ff1f4146107ed578063dc4c90d31461080e575f80fd5b8063c7821978116100ac578063c782197814610790578063d547741f146107af578063d6b25f0b146107ce575f80fd5b8063b2405a3714610745578063c4d66de814610771575f80fd5b80639c6b88a81161011b578063a217fddf11610101578063a217fddf1461056f578063aaf6baaf14610705578063ae44164e14610731575f80fd5b80639c6b88a8146106675780639f5007eb14610686575f80fd5b80638da5cb5b1461055257806391cb46691461056f57806391d148541461058257806392461821146105c6575f80fd5b80634f1ef286116101db57806358885850116101ab578063635578251161019157806363557825146105005780636cab33601461051f578063715018a61461053e575f80fd5b806358885850146104825780635f2e42f6146104d4575f80fd5b80634f1ef286146103f657806352d1902d14610409578063544c2e4f1461041d5780635859734c14610456575f80fd5b80632f2ff15d116102305780633659cfe6116102165780633659cfe6146103725780633f3c297c1461039157806348566a33146103be575f80fd5b80632f2ff15d1461033257806336568abe14610353575f80fd5b806301ffc9a71461026157806304a0fb171461029557806320808892146102d6578063248a9ca314610304575b5f80fd5b34801561026c575f80fd5b5061028061027b366004614b2d565b6108ae565b60405190151581526020015b60405180910390f35b3480156102a0575f80fd5b506102c87fdfbefbf47cfe66b701d8cfdbce1de81c821590819cb07e71cb01b6602fb0ee2781565b60405190815260200161028c565b3480156102e1575f80fd5b506102f56102f0366004614b64565b6108e4565b60405161028c93929190614b92565b34801561030f575f80fd5b506102c861031e366004614c2e565b5f9081526097602052604090206001015490565b34801561033d575f80fd5b5061035161034c366004614c59565b6109e3565b005b34801561035e575f80fd5b5061035161036d366004614c59565b610a0c565b34801561037d575f80fd5b5061035161038c366004614c7c565b610a9d565b34801561039c575f80fd5b506103b06103ab366004614c97565b610c17565b60405161028c929190614ccf565b3480156103c9575f80fd5b5061012d546103de906001600160a01b031681565b6040516001600160a01b03909116815260200161028c565b610351610404366004614df6565b610f39565b348015610414575f80fd5b506102c86110a1565b348015610428575f80fd5b5061043c610437366004614e90565b611165565b60408051600293840b81529190920b60208201520161028c565b348015610461575f80fd5b50610475610470366004614eb3565b6112d3565b60405161028c9190614edc565b34801561048d575f80fd5b506104a161049c366004614f1e565b611457565b60405161028c91908151815260208083015190820152604080830151908201526060918201519181019190915260800190565b3480156104df575f80fd5b506104f36104ee366004614f50565b61151a565b60405161028c9190614f7a565b34801561050b575f80fd5b506103b061051a366004614c97565b61159e565b34801561052a575f80fd5b50610351610539366004614c2e565b61181c565b348015610549575f80fd5b50610351611884565b34801561055d575f80fd5b506033546001600160a01b03166103de565b34801561057a575f80fd5b506102c85f81565b34801561058d575f80fd5b5061028061059c366004614c59565b5f9182526097602090815260408084206001600160a01b0393909316845291905290205460ff1690565b3480156105d1575f80fd5b506106276105e0366004614c2e565b61012f6020525f90815260409020805460018201546002928301546001600160a01b03928316938284169362ffffff600160a01b85041693600160b81b900490910b911685565b604080516001600160a01b039687168152948616602086015262ffffff9093169284019290925260020b606083015291909116608082015260a00161028c565b348015610672575f80fd5b506102c8610681366004614fec565b611897565b348015610691575f80fd5b506106d76106a0366004614c2e565b60e881901c60d082901c60018084161478ffffffffffffffffffffffffffffffffffffffffffffffffff600885901c169193509193565b60408051600295860b81529390940b602084015290151592820192909252606081019190915260800161028c565b348015610710575f80fd5b5061072461071f366004615014565b6118b1565b60405161028c919061507d565b34801561073c575f80fd5b506102c8600281565b348015610750575f80fd5b5061076461075f366004614c7c565b611d11565b60405161028c91906150d6565b34801561077c575f80fd5b5061035161078b366004614c7c565b611e56565b34801561079b575f80fd5b5061043c6107aa366004614e90565b612063565b3480156107ba575f80fd5b506103516107c9366004614c59565b6121fc565b3480156107d9575f80fd5b506103516107e8366004615119565b612220565b3480156107f8575f80fd5b50610801612295565b60405161028c9190615172565b348015610819575f80fd5b5061012e546103de906001600160a01b031681565b348015610839575f80fd5b5061084d610848366004614f1e565b612436565b60405161028c929190615269565b348015610866575f80fd5b50610351610875366004614c7c565b61251c565b348015610885575f80fd5b506108996108943660046154f2565b6125a9565b6040805192835260208301919091520161028c565b5f6001600160e01b03198216637965db0b60e01b14806108de57506301ffc9a760e01b6001600160e01b03198316145b92915050565b5f82815261012f60209081526040808320815160a08101835281546001600160a01b03908116825260018301548082169583019590955262ffffff600160a01b86041682850152600160b81b909404600290810b6060838101919091529201548416608082015261012e54925163be43117f60e01b81528594929391927364e9052dcf51486bf104715ceea830d779c51ca39263be43117f926109949291909116908a9086908b90600401615531565b5f60405180830381865af41580156109ae573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526109d591908101906155db565b935093509350509250925092565b5f828152609760205260409020600101546109fd81612680565b610a07838361268a565b505050565b6001600160a01b0381163314610a8f5760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201527f20726f6c657320666f722073656c66000000000000000000000000000000000060648201526084015b60405180910390fd5b610a99828261272a565b5050565b6001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000163003610b2a5760405162461bcd60e51b815260206004820152602c60248201527f46756e6374696f6e206d7573742062652063616c6c6564207468726f7567682060448201526b19195b1959d85d1958d85b1b60a21b6064820152608401610a86565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316610b857f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc546001600160a01b031690565b6001600160a01b031614610bf05760405162461bcd60e51b815260206004820152602c60248201527f46756e6374696f6e206d7573742062652063616c6c6564207468726f7567682060448201526b6163746976652070726f787960a01b6064820152608401610a86565b610bf9816127ab565b604080515f80825260208201909252610c14918391906127b3565b50565b61012d546040516370be202d60e11b81526001600160a01b0386811660048301526024820186905260448201859052606482018490526060925f9283929091169063e17c405a906084015f60405180830381865afa158015610c7b573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610ca29190810190615708565b90505f815167ffffffffffffffff811115610cbf57610cbf614d1b565b604051908082528060200260200182016040528015610ce8578160200160208202803683370190505b5090505f92505f5b8251811015610e9e575f838281518110610d0c57610d0c6157c5565b60200260200101516040015190505f848381518110610d2d57610d2d6157c5565b60209081029190910101515161012d546040516307c9b93f60e21b8152600481018d9052602481018590526001600160a01b038e811660448301529293505f9290911690631f26e4fc90606401608060405180830381865afa158015610d95573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610db991906157d9565b5061012d546040516306fa80b360e31b81529194505f93506001600160a01b031691506337d4059890610dfb908f908890600401918252602082015260400190565b608060405180830381865afa158015610e16573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e3a9190615813565b50925050505f836001600160801b0316118015610e5e5750801580610e5e57508115155b15610e8e57838689610e6f8161586a565b9a5081518110610e8157610e816157c5565b6020026020010181815250505b505060019092019150610cf09050565b508267ffffffffffffffff811115610eb857610eb8614d1b565b604051908082528060200260200182016040528015610ee1578160200160208202803683370190505b5093505f5b83811015610f2d57818181518110610f0057610f006157c5565b6020026020010151858281518110610f1a57610f1a6157c5565b6020908102919091010152600101610ee6565b50505094509492505050565b6001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000163003610fc65760405162461bcd60e51b815260206004820152602c60248201527f46756e6374696f6e206d7573742062652063616c6c6564207468726f7567682060448201526b19195b1959d85d1958d85b1b60a21b6064820152608401610a86565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166110217f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc546001600160a01b031690565b6001600160a01b03161461108c5760405162461bcd60e51b815260206004820152602c60248201527f46756e6374696f6e206d7573742062652063616c6c6564207468726f7567682060448201526b6163746976652070726f787960a01b6064820152608401610a86565b611095826127ab565b610a99828260016127b3565b5f306001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146111405760405162461bcd60e51b815260206004820152603860248201527f555550535570677261646561626c653a206d757374206e6f742062652063616c60448201527f6c6564207468726f7567682064656c656761746563616c6c00000000000000006064820152608401610a86565b507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc90565b5f82815261012f60209081526040808320815160a08101835281546001600160a01b03908116825260018301548082169583019590955262ffffff600160a01b86041693820193909352600160b81b909304600290810b606085015201548116608083015261012e5483929183916111de911687612953565b5050606084015190925090505f6111f482612a05565b90505f61120083612a26565b9050871561126d57611213846001615882565b965061121f83886158bb565b60020b15611261575f8760020b1361124b578261123c81896158dc565b6112469190615914565b611263565b8261125681896158dc565b61123c906001615882565b865b96508095506112c7565b819650839550828661127f91906158bb565b60020b156112c2575f8660020b136112b75782600161129e82896158dc565b6112a89190615933565b6112b29190615914565b6112c4565b826112a881886158dc565b855b95505b50505050509250929050565b60605f8367ffffffffffffffff8111156112ef576112ef614d1b565b604051908082528060200260200182016040528015611318578160200160208202803683370190505b5090505f805b8581101561144a57611331600187615958565b8103611364576113418288615958565b838281518110611353576113536157c5565b602002602001018181525050611442565b738352fcca6655379bdf3dd7547298ed46997a5ce663cc8c11d088888861138c86600161596b565b6040516001600160e01b031960e087901b1681526004810194909452602484019290925260448301526064820152608401602060405180830381865af41580156113d8573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113fc919061597e565b83828151811061140e5761140e6157c5565b60200260200101818152505082818151811061142c5761142c6157c5565b60200260200101518261143f919061596b565b91505b60010161131e565b50909150505b9392505050565b61147e60405180608001604052805f81526020015f81526020015f81526020015f81525090565b5f61148a838686612a3e565b61012d54604051631b7b4d7960e21b8152919250738352fcca6655379bdf3dd7547298ed46997a5ce691636ded35e4916114d29185916001600160a01b031690600401615995565b608060405180830381865af41580156114ed573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115119190615a83565b95945050505050565b61012d546040516370be202d60e11b81526001600160a01b038481166004830152602482018490525f604483018190526064830152606092169063e17c405a906084015f60405180830381865afa158015611577573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526114509190810190615708565b61012d546040516370be202d60e11b81526001600160a01b0386811660048301526024820186905260448201859052606482018490526060925f9283929091169063e17c405a906084015f60405180830381865afa158015611602573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526116299190810190615708565b90505f815167ffffffffffffffff81111561164657611646614d1b565b60405190808252806020026020018201604052801561166f578160200160208202803683370190505b5090505f92505f5b825181101561178d575f838281518110611693576116936157c5565b60200260200101516040015190505f8483815181106116b4576116b46157c5565b60209081029190910101515161012d546040516306fa80b360e31b8152600481018d9052602481018590529192505f916001600160a01b03909116906337d4059890604401608060405180830381865afa158015611714573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117389190615813565b50925050505f826001600160801b03161180156117525750805b15611782578285886117638161586a565b995081518110611775576117756157c5565b6020026020010181815250505b505050600101611677565b508267ffffffffffffffff8111156117a7576117a7614d1b565b6040519080825280602002602001820160405280156117d0578160200160208202803683370190505b5093505f5b83811015610f2d578181815181106117ef576117ef6157c5565b6020026020010151858281518110611809576118096157c5565b60209081029190910101526001016117d5565b611824612c1c565b5f81815261012f6020526040902080546001600160a01b031990811682556001820180547fffffffffffff0000000000000000000000000000000000000000000000000000169055600290910180549091169055610a9961013082612c76565b61188c612c1c565b6118955f612c81565b565b5f6108de6118aa36849003840184615ac8565b60a0902090565b606060028310156118df57604051635013762560e01b81526004810184905260026024820152604401610a86565b61012d5f9054906101000a90046001600160a01b03166001600160a01b0316630680ecd36040518163ffffffff1660e01b8152600401602060405180830381865afa158015611930573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906119549190615b42565b62ffffff168311156119f35761012d5460408051630680ecd360e01b8152905185926001600160a01b031691630680ecd39160048083019260209291908290030181865afa1580156119a8573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906119cc9190615b42565b604051631e2c46ef60e01b8152600481019290925262ffffff166024820152604401610a86565b815f036119fe575f80fd5b5f8367ffffffffffffffff811115611a1857611a18614d1b565b604051908082528060200260200182016040528015611a6157816020015b604080516060810182525f80825260208083018290529282015282525f19909201910181611a365790505b5090505f805b85811015611b7c57611a7a600187615958565b8114611b1d57738352fcca6655379bdf3dd7547298ed46997a5ce663cc8c11d0888888611aa886600161596b565b6040516001600160e01b031960e087901b1681526004810194909452602484019290925260448301526064820152608401602060405180830381865af4158015611af4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611b18919061597e565b611b27565b611b278288615958565b838281518110611b3957611b396157c5565b60200260200101516040018181525050828181518110611b5b57611b5b6157c5565b60200260200101516040015182611b72919061596b565b9150600101611a67565b505061012e545f90611b97906001600160a01b03168b612953565b50505f8c815261012f602052604080822060010154905163b62d6c3760e01b815260028d810b60048301528c810b602483015284810b60448301528e15156064830152608482018b905260a482018a9052600160b81b90920490910b60c482018190529294509192509073c34372e663a5bd02e68a2d0e4908ad90540ae33c9063b62d6c379060e4015f60405180830381865af4158015611c3a573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611c619190810190615b5d565b90505f5b87811015611d0057818181518110611c7f57611c7f6157c5565b60200260200101515f0151858281518110611c9c57611c9c6157c5565b60200260200101515f019060020b908160020b81525050818181518110611cc557611cc56157c5565b602002602001015160200151858281518110611ce357611ce36157c5565b60209081029190910181015160029290920b910152600101611c65565b50929b9a5050505050505050505050565b60605f611d1f610130612cd2565b90508067ffffffffffffffff811115611d3a57611d3a614d1b565b604051908082528060200260200182016040528015611d7e57816020015b604080518082019091525f8082526020820152815260200190600190039081611d585790505b5091505f5b81811015611e4f575f611d9861013083612cdb565b61012d54604051634b20ccbf60e01b81526001600160a01b038881166004830152602482018490529293505f9290911690634b20ccbf90604401602060405180830381865afa158015611ded573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611e11919061597e565b9050604051806040016040528083815260200182815250858481518110611e3a57611e3a6157c5565b60209081029190910101525050600101611d83565b5050919050565b5f54610100900460ff1615808015611e7457505f54600160ff909116105b80611e8d5750303b158015611e8d57505f5460ff166001145b611eff5760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201527f647920696e697469616c697a65640000000000000000000000000000000000006064820152608401610a86565b5f805460ff191660011790558015611f20575f805461ff0019166101001790555b611f28612ce6565b611f30612d58565b611f38612d58565b6001600160a01b038216611f4a575f80fd5b61012d80546001600160a01b0319166001600160a01b0384169081179091556040805163dc4c90d360e01b8152905163dc4c90d3916004808201926020929091908290030181865afa158015611fa2573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611fc69190615c37565b61012e80546001600160a01b0319166001600160a01b0392909216919091179055611ff15f3361268a565b61201b7fdfbefbf47cfe66b701d8cfdbce1de81c821590819cb07e71cb01b6602fb0ee273361268a565b8015610a99575f805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15050565b5f82815261012f60209081526040808320815160a08101835281546001600160a01b03908116825260018301548082169583019590955262ffffff600160a01b86041693820193909352600160b81b909304600290810b606085015201548116608083015261012e5483929183916120dc911687612953565b5050606084015190925090505f6120f282612a05565b90505f6120fe83612a26565b90505f881561217e575f8560020b12156121485761211c84866158bb565b60020b1561213e578361212f81876158dc565b6121399190615914565b612168565b6121398486615882565b838061215481886158dc565b61215e9190615914565b6121689190615882565b90506121748482615882565b97508196506121ef565b5f8560020b12156121c65761219384866158bb565b60020b156121c05783806121a781886158dc565b6121b19190615914565b6121bb9190615933565b6121db565b846121db565b836121d181876158dc565b6121db9190615914565b905082975083816121ec9190615933565b96505b5050505050509250929050565b5f8281526097602052604090206001015461221681612680565b610a07838361272a565b7fdfbefbf47cfe66b701d8cfdbce1de81c821590819cb07e71cb01b6602fb0ee2761224a81612680565b8261225d6118aa36859003850185615ac8565b14612266575f80fd5b5f83815261012f6020526040902082906122808282615c52565b5061228f905061013084612dc2565b50505050565b60605f6122a3610130612cd2565b90508067ffffffffffffffff8111156122be576122be614d1b565b60405190808252806020026020018201604052801561233e57816020015b61232b60408051608080820183525f808352835160a081018552818152602081810183905294810182905260608101829052918201529091820190815260200160608152602001606081525090565b8152602001906001900390816122dc5790505b5091505f5b81811015612431575f61235861013083612cdb565b5f81815261012f60209081526040808320815160a08101835281546001600160a01b0390811680835260018401548083169684019690965262ffffff600160a01b87041694830194909452600160b81b909404600290810b6060830152909101549092166080830152929350916123ce90612dcd565b5090505f6123df8360200151612dcd565b509050604051806080016040528085815260200184815260200183815260200182815250878681518110612415576124156157c5565b6020026020010181905250848060010195505050505050612343565b505090565b60605f61244285612eeb565b9050825f0361244f578092505b80841061248e57604080515f8082526020820190925290612486565b612473614a43565b81526020019060019003908161246b5790505b509150612514565b5f8161249a858761596b565b116124a557836124af565b6124af8583615958565b90508067ffffffffffffffff8111156124ca576124ca614d1b565b60405190808252806020026020018201604052801561250357816020015b6124f0614a43565b8152602001906001900390816124e85790505b50925061251286868386612f94565b505b935093915050565b612524612c1c565b6001600160a01b0381166125a05760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201527f64647265737300000000000000000000000000000000000000000000000000006064820152608401610a86565b610c1481612c81565b5f83815261012f60209081526040808320815160a08101835281546001600160a01b03908116825260018301548082169583019590955262ffffff600160a01b86041693820193909352600160b81b909304600290810b606085018190529181015490921660808401528392918390612623908390615914565b9050600281900b6126348888615933565b60020b1215612655576040516201b81360e01b815260040160405180910390fd5b816126608888615933565b61266a91906158dc565b62ffffff16935060029450505050935093915050565b610c14813361315d565b5f8281526097602090815260408083206001600160a01b038516845290915290205460ff16610a99575f8281526097602090815260408083206001600160a01b03851684529091529020805460ff191660011790556126e63390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b5f8281526097602090815260408083206001600160a01b038516845290915290205460ff1615610a99575f8281526097602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b610c14612c1c565b7f4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd91435460ff16156127e657610a07836131d1565b826001600160a01b03166352d1902d6040518163ffffffff1660e01b8152600401602060405180830381865afa925050508015612840575060408051601f3d908101601f1916820190925261283d9181019061597e565b60015b6128b25760405162461bcd60e51b815260206004820152602e60248201527f45524331393637557067726164653a206e657720696d706c656d656e7461746960448201527f6f6e206973206e6f7420555550530000000000000000000000000000000000006064820152608401610a86565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc81146129475760405162461bcd60e51b815260206004820152602960248201527f45524331393637557067726164653a20756e737570706f727465642070726f7860448201527f6961626c655555494400000000000000000000000000000000000000000000006064820152608401610a86565b50610a0783838361328f565b5f805f805f612961866132b3565b604051631e2eaeaf60e01b8152600481018290529091505f906001600160a01b03891690631e2eaeaf90602401602060405180830381865afa1580156129a9573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906129cd919061597e565b90506001600160a01b03811695508060a01c60020b945062ffffff8160b81c16935062ffffff8160d01c169250505092959194509250565b5f81600281900b620d89e71981612a1e57612a1e6158a7565b050292915050565b5f81600281900b620d89e881612a1e57612a1e6158a7565b604080516101a0810182525f610120820181815261014083018290526101608301829052610180830182905282528251608080820185528282526020808301849052828601849052606080840185905290850192909252938301829052820181905291810182905260a0810182905260c0810182905260e0810182905261010081019190915260408051610120810190915260e885901c9060d086901c906001808816149080612aef878a8a6132ef565b8152602001612afe878a6133cb565b815261012e546001600160a01b0390811660208084019190915260408084018a9052600288810b606086015287900b608085015285151560a085015261012d54815163d73792a960e01b8152915160c09095019493169263d73792a9926004808401939192918290030181865afa158015612b7b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612b9f919061597e565b815261012d546040805163034c350b60e21b815290516020938401936001600160a01b0390931692630d30d42c92600480820193918290030181865afa158015612beb573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612c0f919061597e565b9052979650505050505050565b6033546001600160a01b031633146118955760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610a86565b5f6114508383613491565b603380546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a35050565b5f6108de825490565b5f611450838361357b565b5f54610100900460ff16612d505760405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b6064820152608401610a86565b6118956135a1565b5f54610100900460ff166118955760405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b6064820152608401610a86565b5f6114508383613614565b60605f6001600160a01b038316612e1b57505060408051808201909152600681527f4e4154495645000000000000000000000000000000000000000000000000000060208201529160129150565b5f839050806001600160a01b03166395d89b416040518163ffffffff1660e01b81526004015f60405180830381865afa158015612e5a573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052612e819190810190615d5d565b9250806001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015612ebf573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612ee39190615dd2565b915050915091565b5f80612ef8610130612cd2565b90505f5b81811015611e4f575f612f1161013083612cdb565b61012d54604051634b20ccbf60e01b81526001600160a01b03888116600483015260248201849052929350911690634b20ccbf90604401602060405180830381865afa158015612f63573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612f87919061597e565b9093019250600101612efc565b5f612fa0610130612cd2565b90505f6040518060a001604052805f81526020018681526020015f81526020018581526020015f81525090505f5b8281108015612fe4575081606001518260400151105b15613154575f612ff661013083612cdb565b61012d54604051634b20ccbf60e01b81526001600160a01b038b8116600483015260248201849052929350911690634b20ccbf90604401602060405180830381865afa158015613048573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061306c919061597e565b608084018190525f036130825750600101612fce565b5f81815261012f60209081526040808320815160a08101835281546001600160a01b03908116825260018301548082169583019590955262ffffff600160a01b860416938201849052600160b81b909404600290810b60608301529091015490921660808301529091036130fa575050600101612fce565b602084015160808501518551613110919061596b565b116131365760808401518451859061312990839061596b565b9052505050600101612fce565b613143898383878a613660565b855260408501525050600101612fce565b50505050505050565b5f8281526097602090815260408083206001600160a01b038516845290915290205460ff16610a995761318f81613831565b61319a836020613843565b6040516020016131ab929190615e09565b60408051601f198184030181529082905262461bcd60e51b8252610a8691600401615e6a565b6001600160a01b0381163b61324e5760405162461bcd60e51b815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201527f6f74206120636f6e7472616374000000000000000000000000000000000000006064820152608401610a86565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc80546001600160a01b0319166001600160a01b0392909216919091179055565b613298836139e6565b5f825111806132a45750805b15610a075761228f8383613a25565b6040515f906132d2908390600690602001918252602082015260400190565b604051602081830303815290604052805190602001209050919050565b61331f60405180608001604052805f6001600160801b031681526020015f81526020015f81526020015f81525090565b61012d546040516307c9b93f60e21b815260048101869052602481018590526001600160a01b0384811660448301525f928392839283921690631f26e4fc90606401608060405180830381865afa15801561337c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906133a091906157d9565b6001600160801b03909316885260208801919091526040870152606086015250929695505050505050565b604080516080810182525f808252602082018190528183018190526060820181905261012d5492516306fa80b360e31b81526004810186905260248101859052919290918291829182916001600160a01b0316906337d4059890604401608060405180830381865afa158015613443573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906134679190615813565b9288526001600160801b039091166020880152151560408701526060860152509295945050505050565b5f818152600183016020526040812054801561356b575f6134b3600183615958565b85549091505f906134c690600190615958565b9050808214613525575f865f0182815481106134e4576134e46157c5565b905f5260205f200154905080875f018481548110613504576135046157c5565b5f918252602080832090910192909255918252600188019052604090208390555b855486908061353657613536615e7c565b600190038181905f5260205f20015f90559055856001015f8681526020019081526020015f205f9055600193505050506108de565b5f9150506108de565b5092915050565b5f825f018281548110613590576135906157c5565b905f5260205f200154905092915050565b5f54610100900460ff1661360b5760405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b6064820152608401610a86565b61189533612c81565b5f81815260018301602052604081205461365957508154600181810184555f8481526020808220909301849055845484825282860190935260409020919091556108de565b505f6108de565b6080820151602083015183515f9283928392101561369e57855160208701516136899190615958565b915081866080015161369b9190615958565b90505b85606001518187604001516136b3919061596b565b11156136d057856040015186606001516136cd9190615958565b90505b5f6136dc89898c613a4a565b61012d546040516370be202d60e11b81526001600160a01b038d81166004830152602482018d905260448201879052606482018690529293505f929091169063e17c405a906084015f60405180830381865afa15801561373e573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526137659190810190615708565b90505f5b815181108015613780575088606001518960400151105b156137e9576137b58c8c8c85858151811061379d5761379d6157c5565b602002602001015160400151878d8f60400151613ac1565b604089018051906137c58261586a565b9052508851896137d48261586a565b905250806137e18161586a565b915050613769565b5080518489608001516137fc9190615958565b6138069190615958565b8851899061381590839061596b565b9052505050506040850151945194989497509395505050505050565b60606108de6001600160a01b03831660145b60605f613851836002615e90565b61385c90600261596b565b67ffffffffffffffff81111561387457613874614d1b565b6040519080825280601f01601f19166020018201604052801561389e576020820181803683370190505b509050600360fc1b815f815181106138b8576138b86157c5565b60200101906001600160f81b03191690815f1a905350600f60fb1b816001815181106138e6576138e66157c5565b60200101906001600160f81b03191690815f1a9053505f613908846002615e90565b61391390600161596b565b90505b6001811115613997577f303132333435363738396162636465660000000000000000000000000000000085600f1660108110613954576139546157c5565b1a60f81b82828151811061396a5761396a6157c5565b60200101906001600160f81b03191690815f1a90535060049490941c9361399081615ea7565b9050613916565b5083156114505760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e746044820152606401610a86565b6139ef816131d1565b6040516001600160a01b038216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b905f90a250565b60606114508383604051806060016040528060278152602001615efa60279139613b10565b613aaa6040518061014001604052805f6001600160a01b031681526020015f60020b815260200160608152602001606081526020015f60ff1681526020015f60ff1681526020015f81526020015f81526020015f81526020015f81525090565b613ab48484613b84565b9050611450828483613c49565b8360e881901c60d082901c600180841614613ae286868c8c8b888888613c86565b613af2868685858b5f0151613eb0565b613b0386868c8b8f8c898989613f79565b5050505050505050505050565b60605f80856001600160a01b031685604051613b2c9190615ebc565b5f60405180830381855af49150503d805f8114613b64576040519150601f19603f3d011682016040523d82523d5f602084013e613b69565b606091505b5091509150613b7a86838387614313565b9695505050505050565b613be46040518061014001604052805f6001600160a01b031681526020015f60020b815260200160608152602001606081526020015f60ff1681526020015f60ff1681526020015f81526020015f81526020015f81526020015f81525090565b61012e54613bfb906001600160a01b031684612953565b505060020b60208301526001600160a01b031681528151613c1b90612dcd565b60ff16608083015260408201526020820151613c3690612dcd565b60ff1660a0830152606082015292915050565b5f80613c558585614393565b60208083015160c087015260409283015160e087015281015161010086015201516101209093019290925250505050565b85888881518110613c9957613c996157c5565b60209081029190910101515284518851899089908110613cbb57613cbb6157c5565b6020026020010151604001906001600160a01b031690816001600160a01b0316815250508460200151888881518110613cf657613cf66157c5565b6020026020010151606001906001600160a01b031690816001600160a01b0316815250508360400151888881518110613d3157613d316157c5565b6020026020010151608001819052508360600151888881518110613d5757613d576157c5565b602002602001015160a001819052508360800151888881518110613d7d57613d7d6157c5565b602002602001015160c0019060ff16908160ff16815250508360a00151888881518110613dac57613dac6157c5565b602002602001015160e0019060ff16908160ff168152505080888881518110613dd757613dd76157c5565b602002602001015161010001901515908115158152505082888881518110613e0157613e016157c5565b6020026020010151610120019060020b908160020b8152505081888881518110613e2d57613e2d6157c5565b6020026020010151610140019060020b908160020b815250508360200151888881518110613e5d57613e5d6157c5565b6020026020010151610160019060020b908160020b815250508460600151888881518110613e8d57613e8d6157c5565b6020026020010151610180019060020b908160020b815250505050505050505050565b5f613eba8461450a565b90505f613ec68461450a565b905082878781518110613edb57613edb6157c5565b60200260200101516101a001906001600160a01b031690816001600160a01b03168152505081878781518110613f1357613f136157c5565b60200260200101516101c001906001600160a01b031690816001600160a01b03168152505080878781518110613f4b57613f4b6157c5565b60200260200101516101e001906001600160a01b031690816001600160a01b03168152505050505050505050565b61012d546040516307c9b93f60e21b815260048101899052602481018890526001600160a01b0387811660448301525f921690631f26e4fc90606401608060405180830381865afa158015613fd0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613ff491906157d9565b505061012d546040516306fa80b360e31b8152600481018c9052602481018b90529293505f926001600160a01b0390911691506337d4059890604401608060405180830381865afa15801561404b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061406f9190615813565b5092505050818b8b81518110614087576140876157c5565b602002602001015161020001906001600160801b031690816001600160801b031681525050878b8b815181106140bf576140bf6157c5565b602002602001015160200181815250508560c001518b8b815181106140e6576140e66157c5565b60200260200101516102a00181815250508561010001518b8b8151811061410f5761410f6157c5565b60200260200101516102c00181815250508560e001518b8b81518110614137576141376157c5565b60200260200101516102e00181815250508561012001518b8b81518110614160576141606157c5565b60200260200101516103000181815250505f61417d888b8b611457565b9050805f01518c8c81518110614195576141956157c5565b602002602001015161022001818152505080602001518c8c815181106141bd576141bd6157c5565b602002602001015161024001818152505080604001518c8c815181106141e5576141e56157c5565b602002602001015161026001818152505080606001518c8c8151811061420d5761420d6157c5565b602002602001015161028001818152505061422c8c8c888887896147cf565b81158c8c81518110614240576142406157c5565b60200260200101516103800190151590811515815250505f8c8c8151811061426a5761426a6157c5565b60200260200101516101c0015190505f8d8d8151811061428c5761428c6157c5565b60200260200101516101e00151905085156142d4576142ac8282876148a1565b8e8e815181106142be576142be6157c5565b6020026020010151610360018181525050614303565b6142df82828761491c565b8e8e815181106142f1576142f16157c5565b60200260200101516103600181815250505b5050505050505050505050505050565b606083156143815782515f0361437a576001600160a01b0385163b61437a5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610a86565b508161438b565b61438b838361496e565b949350505050565b6143bd60405180606001604052805f6001600160a01b031681526020015f81526020015f81525090565b6143e760405180606001604052805f6001600160a01b031681526020015f81526020015f81525090565b60a083205f9084516001600160a01b03908116855260208601518116845261012d546040516370be202d60e11b81528883166004820152602481018490525f604482018190526064820181905293945091169063e17c405a906084015f60405180830381865afa15801561445d573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526144849190810190615708565b90505f5b8151811015614500575f6144ba88858585815181106144a9576144a96157c5565b602002602001015160400151611457565b8051602080890180519092019091528082015190870180519091019052604080820151818901805190910190526060909101519086018051909101905250600101614488565b5050509250929050565b60020b5f60ff82901d80830118620d89e8811115614533576145336345c3193d60e11b84614998565b7001fffcb933bd6fad37aa2d162d1a594001600182160270010000000000000000000000000000000018600282161561457c576ffff97272373d413259a46990580e213a0260801c5b600482161561459b576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b60088216156145ba576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b60108216156145d9576fffcb9843d60f6159c9db58835c9266440260801c5b60208216156145f8576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615614617576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615614636576ffe5dee046a99a2a811c461f1969c30530260801c5b610100821615614656576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615614676576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615614696576ff3392b0822b70005940c7a398e4b70f30260801c5b6108008216156146b6576fe7159475a2c29b7443b29c7fa6e889d90260801c5b6110008216156146d6576fd097f3bdfd2022b8845ad8f792aa58250260801c5b6120008216156146f6576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615614716576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615614736576f31be135f97d08fd981231505542fcfa60260801c5b62010000821615614757576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b62020000821615614777576e5d6af8dedb81196699c329225ee6040260801c5b62040000821615614796576d2216e584f5fa1ea926041bedfe980260801c5b620800008216156147b3576b048a170391f7dc42444e8fa20260801c5b5f8413156147bf575f19045b63ffffffff0160201c9392505050565b5f6147d98561450a565b90505f6147e58561450a565b90508215614844575f888881518110614800576148006157c5565b602002602001015161032001818152505061481c82828661491c565b88888151811061482e5761482e6157c5565b6020026020010151610340018181525050614897565b61484f8282866148a1565b888881518110614861576148616157c5565b60200260200101516103200181815250505f888881518110614885576148856157c5565b60200260200101516103400181815250505b5050505050505050565b5f826001600160a01b0316846001600160a01b031611156148c0579192915b6001600160a01b0384166149127bffffffffffffffffffffffffffffffff000000000000000000000000606085901b166148fa8787615ec7565b6001600160a01b0316866001600160a01b03166149a7565b61438b9190615ee6565b5f826001600160a01b0316846001600160a01b0316111561493b579192915b61438b6001600160801b0383166149528686615ec7565b6001600160a01b03166c010000000000000000000000006149a7565b81511561497e5781518083602001fd5b8060405162461bcd60e51b8152600401610a869190615e6a565b815f528060020b60045260245ffd5b5f838302815f19858709828110838203039150508084116149c6575f80fd5b805f036149d857508290049050611450565b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b604080516103a0810182525f8082526020820181905291810182905260608082018390526080820181905260a082015260c0810182905260e08101829052610100810182905261012081018290526101408101829052610160810182905261018081018290526101a081018290526101c081018290526101e08101829052610200810182905261022081018290526102408101829052610260810182905261028081018290526102a081018290526102c081018290526102e08101829052610300810182905261032081018290526103408101829052610360810182905261038081019190915290565b5f60208284031215614b3d575f80fd5b81356001600160e01b031981168114611450575f80fd5b62ffffff81168114610c14575f80fd5b5f8060408385031215614b75575f80fd5b823591506020830135614b8781614b54565b809150509250929050565b5f606082018560020b83526001600160a01b0385166020840152606060408401528084518083526080850191506020860192505f5b81811015614c21578351805160020b84526001600160a01b0360208201511660208501526040810151604085015260608101516060850152608081015160808501525060a083019250602084019350600181019050614bc7565b5090979650505050505050565b5f60208284031215614c3e575f80fd5b5035919050565b6001600160a01b0381168114610c14575f80fd5b5f8060408385031215614c6a575f80fd5b823591506020830135614b8781614c45565b5f60208284031215614c8c575f80fd5b813561145081614c45565b5f805f8060808587031215614caa575f80fd5b8435614cb581614c45565b966020860135965060408601359560600135945092505050565b604080825283519082018190525f9060208501906060840190835b81811015614d08578351835260209384019390920191600101614cea565b5050602093909301939093525092915050565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff81118282101715614d5257614d52614d1b565b60405290565b6040516060810167ffffffffffffffff81118282101715614d5257614d52614d1b565b6040516080810167ffffffffffffffff81118282101715614d5257614d52614d1b565b604051601f8201601f1916810167ffffffffffffffff81118282101715614dc757614dc7614d1b565b604052919050565b5f67ffffffffffffffff821115614de857614de8614d1b565b50601f01601f191660200190565b5f8060408385031215614e07575f80fd5b8235614e1281614c45565b9150602083013567ffffffffffffffff811115614e2d575f80fd5b8301601f81018513614e3d575f80fd5b8035614e50614e4b82614dcf565b614d9e565b818152866020838501011115614e64575f80fd5b816020840160208301375f602083830101528093505050509250929050565b8015158114610c14575f80fd5b5f8060408385031215614ea1575f80fd5b823591506020830135614b8781614e83565b5f805f60608486031215614ec5575f80fd5b505081359360208301359350604090920135919050565b602080825282518282018190525f918401906040840190835b81811015614f13578351835260209384019390920191600101614ef5565b509095945050505050565b5f805f60608486031215614f30575f80fd5b8335614f3b81614c45565b95602085013595506040909401359392505050565b5f8060408385031215614f61575f80fd5b8235614f6c81614c45565b946020939093013593505050565b602080825282518282018190525f918401906040840190835b81811015614f135783516001600160801b038151168452602081015160208501526040810151604085015250606083019250602084019350600181019050614f93565b5f60a08284031215614fe6575f80fd5b50919050565b5f60a08284031215614ffc575f80fd5b6114508383614fd6565b8060020b8114610c14575f80fd5b5f805f805f805f60e0888a03121561502a575f80fd5b87359650602088013561503c81614e83565b9550604088013561504c81615006565b9450606088013561505c81615006565b9699959850939660808101359560a0820135955060c0909101359350915050565b602080825282518282018190525f918401906040840190835b81811015614f13578351805160020b8452602081015160020b60208501526040810151604085015250606083019250602084019350600181019050615096565b602080825282518282018190525f918401906040840190835b81811015614f135783518051845260209081015181850152909301926040909201916001016150ef565b5f8060c0838503121561512a575f80fd5b8235915061513b8460208501614fd6565b90509250929050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b5f602082016020835280845180835260408501915060408160051b8601019250602086015f5b8281101561525d57603f19878603018452815180518652602081015161520f60208801826001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b50604081015161010060c088015261522b610100880182615144565b90506060820151915086810360e08801526152468183615144565b965050506020938401939190910190600101615198565b50929695505050505050565b5f604082016040835280855180835260608501915060608160051b8601019250602087015f5b828110156154de57605f198786030184528151805186526020810151602087015260408101516152ca60408801826001600160a01b03169052565b5060608101516152e560608801826001600160a01b03169052565b5060808101516103a060808801526153016103a0880182615144565b905060a082015187820360a089015261531a8282615144565b91505060c082015161533160c089018260ff169052565b5060e082015161534660e089018260ff169052565b5061010082015161535c61010089018215159052565b5061012082015161537361012089018260020b9052565b5061014082015161538a61014089018260020b9052565b506101608201516153a161016089018260020b9052565b506101808201516153b861018089018260020b9052565b506101a08201516153d56101a08901826001600160a01b03169052565b506101c08201516153f26101c08901826001600160a01b03169052565b506101e082015161540f6101e08901826001600160a01b03169052565b5061020082015161542c6102008901826001600160801b03169052565b506102208201516102208801526102408201516102408801526102608201516102608801526102808201516102808801526102a08201516102a08801526102c08201516102c08801526102e08201516102e088015261030082015161030088015261032082015161032088015261034082015161034088015261036082015161036088015261038082015191506154c861038088018315159052565b955050602093840193919091019060010161528f565b505050506020929092019290925292915050565b5f805f60608486031215615504575f80fd5b83359250602084013561551681615006565b9150604084013561552681615006565b809150509250925092565b6001600160a01b03851681526020810184905261010081016155a460408301856001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b62ffffff831660e083015295945050505050565b5f67ffffffffffffffff8211156155d1576155d1614d1b565b5060051b60200190565b5f805f606084860312156155ed575f80fd5b83516155f881615006565b602085015190935061560981614c45565b604085015190925067ffffffffffffffff811115615625575f80fd5b8401601f81018613615635575f80fd5b8051615643614e4b826155b8565b80828252602082019150602060a08402850101925088831115615664575f80fd5b6020840193505b828410156156df5760a0848a031215615682575f80fd5b61568a614d2f565b845161569581615006565b815260208501516156a581614c45565b60208281019190915260408681015190830152606080870151908301526080808701519083015290835260a090940193919091019061566b565b809450505050509250925092565b80516001600160801b0381168114615703575f80fd5b919050565b5f60208284031215615718575f80fd5b815167ffffffffffffffff81111561572e575f80fd5b8201601f8101841361573e575f80fd5b805161574c614e4b826155b8565b8082825260208201915060206060840285010192508683111561576d575f80fd5b6020840193505b82841015613b7a576060848803121561578b575f80fd5b615793614d58565b61579c856156ed565b815260208581015181830152604080870151908301529083526060909401939190910190615774565b634e487b7160e01b5f52603260045260245ffd5b5f805f80608085870312156157ec575f80fd5b6157f5856156ed565b60208601516040870151606090970151919890975090945092505050565b5f805f8060808587031215615826575f80fd5b84519350615836602086016156ed565b9250604085015161584681614e83565b6060959095015193969295505050565b634e487b7160e01b5f52601160045260245ffd5b5f6001820161587b5761587b615856565b5060010190565b600281810b9083900b01627fffff8113627fffff19821217156108de576108de615856565b634e487b7160e01b5f52601260045260245ffd5b5f8260020b806158cd576158cd6158a7565b808360020b0791505092915050565b5f8160020b8360020b806158f2576158f26158a7565b627fffff1982145f198214161561590b5761590b615856565b90059392505050565b5f8260020b8260020b028060020b915080821461357457613574615856565b600282810b9082900b03627fffff198112627fffff821317156108de576108de615856565b818103818111156108de576108de615856565b808201808211156108de576108de615856565b5f6020828403121561598e575f80fd5b5051919050565b825180516001600160801b03168252602080820151908301526040808201519083015260609081015190820152610200810160208481015180516080850152908101516001600160801b031660a08401526040810151151560c0840152606081015160e08401525060408401516001600160a01b0381166101008401525060608401516101208301526080840151615a3361014084018260020b9052565b5060a0840151615a4961016084018260020b9052565b5060c0840151151561018083015260e08401516101a08301526101008401516101c08301526001600160a01b0383166101e0830152611450565b5f6080828403128015615a94575f80fd5b50615a9d614d7b565b8251815260208084015190820152604080840151908201526060928301519281019290925250919050565b5f60a0828403128015615ad9575f80fd5b50615ae2614d2f565b8235615aed81614c45565b81526020830135615afd81614c45565b60208201526040830135615b1081614b54565b60408201526060830135615b2381615006565b60608201526080830135615b3681614c45565b60808201529392505050565b5f60208284031215615b52575f80fd5b815161145081614b54565b5f60208284031215615b6d575f80fd5b815167ffffffffffffffff811115615b83575f80fd5b8201601f81018413615b93575f80fd5b8051615ba1614e4b826155b8565b8082825260208201915060208360071b850101925086831115615bc2575f80fd5b6020840193505b82841015613b7a5760808488031215615be0575f80fd5b615be8614d7b565b8451615bf381615006565b81526020850151615c0381615006565b602082015260408581015190820152615c1e606086016156ed565b6060820152825260809390930192602090910190615bc9565b5f60208284031215615c47575f80fd5b815161145081614c45565b8135615c5d81614c45565b81546001600160a01b0319166001600160a01b03821617825550600181016020830135615c8981614c45565b81546001600160a01b0319166001600160a01b038216178255506040830135615cb181614b54565b81546060850135615cc181615006565b8060b81b79ffffff00000000000000000000000000000000000000000000001676ffffff00000000000000000000000000000000000000008460a01b167fffffffffffff000000000000ffffffffffffffffffffffffffffffffffffffff841617178455505050505f6080830135615d3881614c45565b6002830180546001600160a01b0319166001600160a01b03831617905590508061228f565b5f60208284031215615d6d575f80fd5b815167ffffffffffffffff811115615d83575f80fd5b8201601f81018413615d93575f80fd5b8051615da1614e4b82614dcf565b818152856020838501011115615db5575f80fd5b8160208401602083015e5f91810160200191909152949350505050565b5f60208284031215615de2575f80fd5b815160ff81168114611450575f80fd5b5f81518060208401855e5f93019283525090919050565b7f416363657373436f6e74726f6c3a206163636f756e742000000000000000000081525f615e3a6017830185615df2565b7f206973206d697373696e6720726f6c652000000000000000000000000000000081526115116011820185615df2565b602081525f6114506020830184615144565b634e487b7160e01b5f52603160045260245ffd5b80820281158282048414176108de576108de615856565b5f81615eb557615eb5615856565b505f190190565b5f6114508284615df2565b6001600160a01b0382811682821603908111156108de576108de615856565b5f82615ef457615ef46158a7565b50049056fe416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564a26469706673582212206ec2968168f07aa654128914d5e1b84f57f31e85718e7036dfbd4972dc07a90464736f6c634300081a0033
Deployed Bytecode
0x60806040526004361061025d575f3560e01c80638da5cb5b1161014b578063b2405a37116100c6578063d88ff1f41161007c578063eb33b75011610062578063eb33b7501461082e578063f2fde38b1461085b578063ffa2505b1461087a575f80fd5b8063d88ff1f4146107ed578063dc4c90d31461080e575f80fd5b8063c7821978116100ac578063c782197814610790578063d547741f146107af578063d6b25f0b146107ce575f80fd5b8063b2405a3714610745578063c4d66de814610771575f80fd5b80639c6b88a81161011b578063a217fddf11610101578063a217fddf1461056f578063aaf6baaf14610705578063ae44164e14610731575f80fd5b80639c6b88a8146106675780639f5007eb14610686575f80fd5b80638da5cb5b1461055257806391cb46691461056f57806391d148541461058257806392461821146105c6575f80fd5b80634f1ef286116101db57806358885850116101ab578063635578251161019157806363557825146105005780636cab33601461051f578063715018a61461053e575f80fd5b806358885850146104825780635f2e42f6146104d4575f80fd5b80634f1ef286146103f657806352d1902d14610409578063544c2e4f1461041d5780635859734c14610456575f80fd5b80632f2ff15d116102305780633659cfe6116102165780633659cfe6146103725780633f3c297c1461039157806348566a33146103be575f80fd5b80632f2ff15d1461033257806336568abe14610353575f80fd5b806301ffc9a71461026157806304a0fb171461029557806320808892146102d6578063248a9ca314610304575b5f80fd5b34801561026c575f80fd5b5061028061027b366004614b2d565b6108ae565b60405190151581526020015b60405180910390f35b3480156102a0575f80fd5b506102c87fdfbefbf47cfe66b701d8cfdbce1de81c821590819cb07e71cb01b6602fb0ee2781565b60405190815260200161028c565b3480156102e1575f80fd5b506102f56102f0366004614b64565b6108e4565b60405161028c93929190614b92565b34801561030f575f80fd5b506102c861031e366004614c2e565b5f9081526097602052604090206001015490565b34801561033d575f80fd5b5061035161034c366004614c59565b6109e3565b005b34801561035e575f80fd5b5061035161036d366004614c59565b610a0c565b34801561037d575f80fd5b5061035161038c366004614c7c565b610a9d565b34801561039c575f80fd5b506103b06103ab366004614c97565b610c17565b60405161028c929190614ccf565b3480156103c9575f80fd5b5061012d546103de906001600160a01b031681565b6040516001600160a01b03909116815260200161028c565b610351610404366004614df6565b610f39565b348015610414575f80fd5b506102c86110a1565b348015610428575f80fd5b5061043c610437366004614e90565b611165565b60408051600293840b81529190920b60208201520161028c565b348015610461575f80fd5b50610475610470366004614eb3565b6112d3565b60405161028c9190614edc565b34801561048d575f80fd5b506104a161049c366004614f1e565b611457565b60405161028c91908151815260208083015190820152604080830151908201526060918201519181019190915260800190565b3480156104df575f80fd5b506104f36104ee366004614f50565b61151a565b60405161028c9190614f7a565b34801561050b575f80fd5b506103b061051a366004614c97565b61159e565b34801561052a575f80fd5b50610351610539366004614c2e565b61181c565b348015610549575f80fd5b50610351611884565b34801561055d575f80fd5b506033546001600160a01b03166103de565b34801561057a575f80fd5b506102c85f81565b34801561058d575f80fd5b5061028061059c366004614c59565b5f9182526097602090815260408084206001600160a01b0393909316845291905290205460ff1690565b3480156105d1575f80fd5b506106276105e0366004614c2e565b61012f6020525f90815260409020805460018201546002928301546001600160a01b03928316938284169362ffffff600160a01b85041693600160b81b900490910b911685565b604080516001600160a01b039687168152948616602086015262ffffff9093169284019290925260020b606083015291909116608082015260a00161028c565b348015610672575f80fd5b506102c8610681366004614fec565b611897565b348015610691575f80fd5b506106d76106a0366004614c2e565b60e881901c60d082901c60018084161478ffffffffffffffffffffffffffffffffffffffffffffffffff600885901c169193509193565b60408051600295860b81529390940b602084015290151592820192909252606081019190915260800161028c565b348015610710575f80fd5b5061072461071f366004615014565b6118b1565b60405161028c919061507d565b34801561073c575f80fd5b506102c8600281565b348015610750575f80fd5b5061076461075f366004614c7c565b611d11565b60405161028c91906150d6565b34801561077c575f80fd5b5061035161078b366004614c7c565b611e56565b34801561079b575f80fd5b5061043c6107aa366004614e90565b612063565b3480156107ba575f80fd5b506103516107c9366004614c59565b6121fc565b3480156107d9575f80fd5b506103516107e8366004615119565b612220565b3480156107f8575f80fd5b50610801612295565b60405161028c9190615172565b348015610819575f80fd5b5061012e546103de906001600160a01b031681565b348015610839575f80fd5b5061084d610848366004614f1e565b612436565b60405161028c929190615269565b348015610866575f80fd5b50610351610875366004614c7c565b61251c565b348015610885575f80fd5b506108996108943660046154f2565b6125a9565b6040805192835260208301919091520161028c565b5f6001600160e01b03198216637965db0b60e01b14806108de57506301ffc9a760e01b6001600160e01b03198316145b92915050565b5f82815261012f60209081526040808320815160a08101835281546001600160a01b03908116825260018301548082169583019590955262ffffff600160a01b86041682850152600160b81b909404600290810b6060838101919091529201548416608082015261012e54925163be43117f60e01b81528594929391927364e9052dcf51486bf104715ceea830d779c51ca39263be43117f926109949291909116908a9086908b90600401615531565b5f60405180830381865af41580156109ae573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526109d591908101906155db565b935093509350509250925092565b5f828152609760205260409020600101546109fd81612680565b610a07838361268a565b505050565b6001600160a01b0381163314610a8f5760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201527f20726f6c657320666f722073656c66000000000000000000000000000000000060648201526084015b60405180910390fd5b610a99828261272a565b5050565b6001600160a01b037f000000000000000000000000ba7eb803eab15052df7e5c48508f9bec21cef50d163003610b2a5760405162461bcd60e51b815260206004820152602c60248201527f46756e6374696f6e206d7573742062652063616c6c6564207468726f7567682060448201526b19195b1959d85d1958d85b1b60a21b6064820152608401610a86565b7f000000000000000000000000ba7eb803eab15052df7e5c48508f9bec21cef50d6001600160a01b0316610b857f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc546001600160a01b031690565b6001600160a01b031614610bf05760405162461bcd60e51b815260206004820152602c60248201527f46756e6374696f6e206d7573742062652063616c6c6564207468726f7567682060448201526b6163746976652070726f787960a01b6064820152608401610a86565b610bf9816127ab565b604080515f80825260208201909252610c14918391906127b3565b50565b61012d546040516370be202d60e11b81526001600160a01b0386811660048301526024820186905260448201859052606482018490526060925f9283929091169063e17c405a906084015f60405180830381865afa158015610c7b573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610ca29190810190615708565b90505f815167ffffffffffffffff811115610cbf57610cbf614d1b565b604051908082528060200260200182016040528015610ce8578160200160208202803683370190505b5090505f92505f5b8251811015610e9e575f838281518110610d0c57610d0c6157c5565b60200260200101516040015190505f848381518110610d2d57610d2d6157c5565b60209081029190910101515161012d546040516307c9b93f60e21b8152600481018d9052602481018590526001600160a01b038e811660448301529293505f9290911690631f26e4fc90606401608060405180830381865afa158015610d95573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610db991906157d9565b5061012d546040516306fa80b360e31b81529194505f93506001600160a01b031691506337d4059890610dfb908f908890600401918252602082015260400190565b608060405180830381865afa158015610e16573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e3a9190615813565b50925050505f836001600160801b0316118015610e5e5750801580610e5e57508115155b15610e8e57838689610e6f8161586a565b9a5081518110610e8157610e816157c5565b6020026020010181815250505b505060019092019150610cf09050565b508267ffffffffffffffff811115610eb857610eb8614d1b565b604051908082528060200260200182016040528015610ee1578160200160208202803683370190505b5093505f5b83811015610f2d57818181518110610f0057610f006157c5565b6020026020010151858281518110610f1a57610f1a6157c5565b6020908102919091010152600101610ee6565b50505094509492505050565b6001600160a01b037f000000000000000000000000ba7eb803eab15052df7e5c48508f9bec21cef50d163003610fc65760405162461bcd60e51b815260206004820152602c60248201527f46756e6374696f6e206d7573742062652063616c6c6564207468726f7567682060448201526b19195b1959d85d1958d85b1b60a21b6064820152608401610a86565b7f000000000000000000000000ba7eb803eab15052df7e5c48508f9bec21cef50d6001600160a01b03166110217f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc546001600160a01b031690565b6001600160a01b03161461108c5760405162461bcd60e51b815260206004820152602c60248201527f46756e6374696f6e206d7573742062652063616c6c6564207468726f7567682060448201526b6163746976652070726f787960a01b6064820152608401610a86565b611095826127ab565b610a99828260016127b3565b5f306001600160a01b037f000000000000000000000000ba7eb803eab15052df7e5c48508f9bec21cef50d16146111405760405162461bcd60e51b815260206004820152603860248201527f555550535570677261646561626c653a206d757374206e6f742062652063616c60448201527f6c6564207468726f7567682064656c656761746563616c6c00000000000000006064820152608401610a86565b507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc90565b5f82815261012f60209081526040808320815160a08101835281546001600160a01b03908116825260018301548082169583019590955262ffffff600160a01b86041693820193909352600160b81b909304600290810b606085015201548116608083015261012e5483929183916111de911687612953565b5050606084015190925090505f6111f482612a05565b90505f61120083612a26565b9050871561126d57611213846001615882565b965061121f83886158bb565b60020b15611261575f8760020b1361124b578261123c81896158dc565b6112469190615914565b611263565b8261125681896158dc565b61123c906001615882565b865b96508095506112c7565b819650839550828661127f91906158bb565b60020b156112c2575f8660020b136112b75782600161129e82896158dc565b6112a89190615933565b6112b29190615914565b6112c4565b826112a881886158dc565b855b95505b50505050509250929050565b60605f8367ffffffffffffffff8111156112ef576112ef614d1b565b604051908082528060200260200182016040528015611318578160200160208202803683370190505b5090505f805b8581101561144a57611331600187615958565b8103611364576113418288615958565b838281518110611353576113536157c5565b602002602001018181525050611442565b738352fcca6655379bdf3dd7547298ed46997a5ce663cc8c11d088888861138c86600161596b565b6040516001600160e01b031960e087901b1681526004810194909452602484019290925260448301526064820152608401602060405180830381865af41580156113d8573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113fc919061597e565b83828151811061140e5761140e6157c5565b60200260200101818152505082818151811061142c5761142c6157c5565b60200260200101518261143f919061596b565b91505b60010161131e565b50909150505b9392505050565b61147e60405180608001604052805f81526020015f81526020015f81526020015f81525090565b5f61148a838686612a3e565b61012d54604051631b7b4d7960e21b8152919250738352fcca6655379bdf3dd7547298ed46997a5ce691636ded35e4916114d29185916001600160a01b031690600401615995565b608060405180830381865af41580156114ed573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115119190615a83565b95945050505050565b61012d546040516370be202d60e11b81526001600160a01b038481166004830152602482018490525f604483018190526064830152606092169063e17c405a906084015f60405180830381865afa158015611577573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526114509190810190615708565b61012d546040516370be202d60e11b81526001600160a01b0386811660048301526024820186905260448201859052606482018490526060925f9283929091169063e17c405a906084015f60405180830381865afa158015611602573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526116299190810190615708565b90505f815167ffffffffffffffff81111561164657611646614d1b565b60405190808252806020026020018201604052801561166f578160200160208202803683370190505b5090505f92505f5b825181101561178d575f838281518110611693576116936157c5565b60200260200101516040015190505f8483815181106116b4576116b46157c5565b60209081029190910101515161012d546040516306fa80b360e31b8152600481018d9052602481018590529192505f916001600160a01b03909116906337d4059890604401608060405180830381865afa158015611714573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117389190615813565b50925050505f826001600160801b03161180156117525750805b15611782578285886117638161586a565b995081518110611775576117756157c5565b6020026020010181815250505b505050600101611677565b508267ffffffffffffffff8111156117a7576117a7614d1b565b6040519080825280602002602001820160405280156117d0578160200160208202803683370190505b5093505f5b83811015610f2d578181815181106117ef576117ef6157c5565b6020026020010151858281518110611809576118096157c5565b60209081029190910101526001016117d5565b611824612c1c565b5f81815261012f6020526040902080546001600160a01b031990811682556001820180547fffffffffffff0000000000000000000000000000000000000000000000000000169055600290910180549091169055610a9961013082612c76565b61188c612c1c565b6118955f612c81565b565b5f6108de6118aa36849003840184615ac8565b60a0902090565b606060028310156118df57604051635013762560e01b81526004810184905260026024820152604401610a86565b61012d5f9054906101000a90046001600160a01b03166001600160a01b0316630680ecd36040518163ffffffff1660e01b8152600401602060405180830381865afa158015611930573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906119549190615b42565b62ffffff168311156119f35761012d5460408051630680ecd360e01b8152905185926001600160a01b031691630680ecd39160048083019260209291908290030181865afa1580156119a8573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906119cc9190615b42565b604051631e2c46ef60e01b8152600481019290925262ffffff166024820152604401610a86565b815f036119fe575f80fd5b5f8367ffffffffffffffff811115611a1857611a18614d1b565b604051908082528060200260200182016040528015611a6157816020015b604080516060810182525f80825260208083018290529282015282525f19909201910181611a365790505b5090505f805b85811015611b7c57611a7a600187615958565b8114611b1d57738352fcca6655379bdf3dd7547298ed46997a5ce663cc8c11d0888888611aa886600161596b565b6040516001600160e01b031960e087901b1681526004810194909452602484019290925260448301526064820152608401602060405180830381865af4158015611af4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611b18919061597e565b611b27565b611b278288615958565b838281518110611b3957611b396157c5565b60200260200101516040018181525050828181518110611b5b57611b5b6157c5565b60200260200101516040015182611b72919061596b565b9150600101611a67565b505061012e545f90611b97906001600160a01b03168b612953565b50505f8c815261012f602052604080822060010154905163b62d6c3760e01b815260028d810b60048301528c810b602483015284810b60448301528e15156064830152608482018b905260a482018a9052600160b81b90920490910b60c482018190529294509192509073c34372e663a5bd02e68a2d0e4908ad90540ae33c9063b62d6c379060e4015f60405180830381865af4158015611c3a573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611c619190810190615b5d565b90505f5b87811015611d0057818181518110611c7f57611c7f6157c5565b60200260200101515f0151858281518110611c9c57611c9c6157c5565b60200260200101515f019060020b908160020b81525050818181518110611cc557611cc56157c5565b602002602001015160200151858281518110611ce357611ce36157c5565b60209081029190910181015160029290920b910152600101611c65565b50929b9a5050505050505050505050565b60605f611d1f610130612cd2565b90508067ffffffffffffffff811115611d3a57611d3a614d1b565b604051908082528060200260200182016040528015611d7e57816020015b604080518082019091525f8082526020820152815260200190600190039081611d585790505b5091505f5b81811015611e4f575f611d9861013083612cdb565b61012d54604051634b20ccbf60e01b81526001600160a01b038881166004830152602482018490529293505f9290911690634b20ccbf90604401602060405180830381865afa158015611ded573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611e11919061597e565b9050604051806040016040528083815260200182815250858481518110611e3a57611e3a6157c5565b60209081029190910101525050600101611d83565b5050919050565b5f54610100900460ff1615808015611e7457505f54600160ff909116105b80611e8d5750303b158015611e8d57505f5460ff166001145b611eff5760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201527f647920696e697469616c697a65640000000000000000000000000000000000006064820152608401610a86565b5f805460ff191660011790558015611f20575f805461ff0019166101001790555b611f28612ce6565b611f30612d58565b611f38612d58565b6001600160a01b038216611f4a575f80fd5b61012d80546001600160a01b0319166001600160a01b0384169081179091556040805163dc4c90d360e01b8152905163dc4c90d3916004808201926020929091908290030181865afa158015611fa2573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611fc69190615c37565b61012e80546001600160a01b0319166001600160a01b0392909216919091179055611ff15f3361268a565b61201b7fdfbefbf47cfe66b701d8cfdbce1de81c821590819cb07e71cb01b6602fb0ee273361268a565b8015610a99575f805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15050565b5f82815261012f60209081526040808320815160a08101835281546001600160a01b03908116825260018301548082169583019590955262ffffff600160a01b86041693820193909352600160b81b909304600290810b606085015201548116608083015261012e5483929183916120dc911687612953565b5050606084015190925090505f6120f282612a05565b90505f6120fe83612a26565b90505f881561217e575f8560020b12156121485761211c84866158bb565b60020b1561213e578361212f81876158dc565b6121399190615914565b612168565b6121398486615882565b838061215481886158dc565b61215e9190615914565b6121689190615882565b90506121748482615882565b97508196506121ef565b5f8560020b12156121c65761219384866158bb565b60020b156121c05783806121a781886158dc565b6121b19190615914565b6121bb9190615933565b6121db565b846121db565b836121d181876158dc565b6121db9190615914565b905082975083816121ec9190615933565b96505b5050505050509250929050565b5f8281526097602052604090206001015461221681612680565b610a07838361272a565b7fdfbefbf47cfe66b701d8cfdbce1de81c821590819cb07e71cb01b6602fb0ee2761224a81612680565b8261225d6118aa36859003850185615ac8565b14612266575f80fd5b5f83815261012f6020526040902082906122808282615c52565b5061228f905061013084612dc2565b50505050565b60605f6122a3610130612cd2565b90508067ffffffffffffffff8111156122be576122be614d1b565b60405190808252806020026020018201604052801561233e57816020015b61232b60408051608080820183525f808352835160a081018552818152602081810183905294810182905260608101829052918201529091820190815260200160608152602001606081525090565b8152602001906001900390816122dc5790505b5091505f5b81811015612431575f61235861013083612cdb565b5f81815261012f60209081526040808320815160a08101835281546001600160a01b0390811680835260018401548083169684019690965262ffffff600160a01b87041694830194909452600160b81b909404600290810b6060830152909101549092166080830152929350916123ce90612dcd565b5090505f6123df8360200151612dcd565b509050604051806080016040528085815260200184815260200183815260200182815250878681518110612415576124156157c5565b6020026020010181905250848060010195505050505050612343565b505090565b60605f61244285612eeb565b9050825f0361244f578092505b80841061248e57604080515f8082526020820190925290612486565b612473614a43565b81526020019060019003908161246b5790505b509150612514565b5f8161249a858761596b565b116124a557836124af565b6124af8583615958565b90508067ffffffffffffffff8111156124ca576124ca614d1b565b60405190808252806020026020018201604052801561250357816020015b6124f0614a43565b8152602001906001900390816124e85790505b50925061251286868386612f94565b505b935093915050565b612524612c1c565b6001600160a01b0381166125a05760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201527f64647265737300000000000000000000000000000000000000000000000000006064820152608401610a86565b610c1481612c81565b5f83815261012f60209081526040808320815160a08101835281546001600160a01b03908116825260018301548082169583019590955262ffffff600160a01b86041693820193909352600160b81b909304600290810b606085018190529181015490921660808401528392918390612623908390615914565b9050600281900b6126348888615933565b60020b1215612655576040516201b81360e01b815260040160405180910390fd5b816126608888615933565b61266a91906158dc565b62ffffff16935060029450505050935093915050565b610c14813361315d565b5f8281526097602090815260408083206001600160a01b038516845290915290205460ff16610a99575f8281526097602090815260408083206001600160a01b03851684529091529020805460ff191660011790556126e63390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b5f8281526097602090815260408083206001600160a01b038516845290915290205460ff1615610a99575f8281526097602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b610c14612c1c565b7f4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd91435460ff16156127e657610a07836131d1565b826001600160a01b03166352d1902d6040518163ffffffff1660e01b8152600401602060405180830381865afa925050508015612840575060408051601f3d908101601f1916820190925261283d9181019061597e565b60015b6128b25760405162461bcd60e51b815260206004820152602e60248201527f45524331393637557067726164653a206e657720696d706c656d656e7461746960448201527f6f6e206973206e6f7420555550530000000000000000000000000000000000006064820152608401610a86565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc81146129475760405162461bcd60e51b815260206004820152602960248201527f45524331393637557067726164653a20756e737570706f727465642070726f7860448201527f6961626c655555494400000000000000000000000000000000000000000000006064820152608401610a86565b50610a0783838361328f565b5f805f805f612961866132b3565b604051631e2eaeaf60e01b8152600481018290529091505f906001600160a01b03891690631e2eaeaf90602401602060405180830381865afa1580156129a9573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906129cd919061597e565b90506001600160a01b03811695508060a01c60020b945062ffffff8160b81c16935062ffffff8160d01c169250505092959194509250565b5f81600281900b620d89e71981612a1e57612a1e6158a7565b050292915050565b5f81600281900b620d89e881612a1e57612a1e6158a7565b604080516101a0810182525f610120820181815261014083018290526101608301829052610180830182905282528251608080820185528282526020808301849052828601849052606080840185905290850192909252938301829052820181905291810182905260a0810182905260c0810182905260e0810182905261010081019190915260408051610120810190915260e885901c9060d086901c906001808816149080612aef878a8a6132ef565b8152602001612afe878a6133cb565b815261012e546001600160a01b0390811660208084019190915260408084018a9052600288810b606086015287900b608085015285151560a085015261012d54815163d73792a960e01b8152915160c09095019493169263d73792a9926004808401939192918290030181865afa158015612b7b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612b9f919061597e565b815261012d546040805163034c350b60e21b815290516020938401936001600160a01b0390931692630d30d42c92600480820193918290030181865afa158015612beb573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612c0f919061597e565b9052979650505050505050565b6033546001600160a01b031633146118955760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610a86565b5f6114508383613491565b603380546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a35050565b5f6108de825490565b5f611450838361357b565b5f54610100900460ff16612d505760405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b6064820152608401610a86565b6118956135a1565b5f54610100900460ff166118955760405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b6064820152608401610a86565b5f6114508383613614565b60605f6001600160a01b038316612e1b57505060408051808201909152600681527f4e4154495645000000000000000000000000000000000000000000000000000060208201529160129150565b5f839050806001600160a01b03166395d89b416040518163ffffffff1660e01b81526004015f60405180830381865afa158015612e5a573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052612e819190810190615d5d565b9250806001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015612ebf573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612ee39190615dd2565b915050915091565b5f80612ef8610130612cd2565b90505f5b81811015611e4f575f612f1161013083612cdb565b61012d54604051634b20ccbf60e01b81526001600160a01b03888116600483015260248201849052929350911690634b20ccbf90604401602060405180830381865afa158015612f63573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612f87919061597e565b9093019250600101612efc565b5f612fa0610130612cd2565b90505f6040518060a001604052805f81526020018681526020015f81526020018581526020015f81525090505f5b8281108015612fe4575081606001518260400151105b15613154575f612ff661013083612cdb565b61012d54604051634b20ccbf60e01b81526001600160a01b038b8116600483015260248201849052929350911690634b20ccbf90604401602060405180830381865afa158015613048573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061306c919061597e565b608084018190525f036130825750600101612fce565b5f81815261012f60209081526040808320815160a08101835281546001600160a01b03908116825260018301548082169583019590955262ffffff600160a01b860416938201849052600160b81b909404600290810b60608301529091015490921660808301529091036130fa575050600101612fce565b602084015160808501518551613110919061596b565b116131365760808401518451859061312990839061596b565b9052505050600101612fce565b613143898383878a613660565b855260408501525050600101612fce565b50505050505050565b5f8281526097602090815260408083206001600160a01b038516845290915290205460ff16610a995761318f81613831565b61319a836020613843565b6040516020016131ab929190615e09565b60408051601f198184030181529082905262461bcd60e51b8252610a8691600401615e6a565b6001600160a01b0381163b61324e5760405162461bcd60e51b815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201527f6f74206120636f6e7472616374000000000000000000000000000000000000006064820152608401610a86565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc80546001600160a01b0319166001600160a01b0392909216919091179055565b613298836139e6565b5f825111806132a45750805b15610a075761228f8383613a25565b6040515f906132d2908390600690602001918252602082015260400190565b604051602081830303815290604052805190602001209050919050565b61331f60405180608001604052805f6001600160801b031681526020015f81526020015f81526020015f81525090565b61012d546040516307c9b93f60e21b815260048101869052602481018590526001600160a01b0384811660448301525f928392839283921690631f26e4fc90606401608060405180830381865afa15801561337c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906133a091906157d9565b6001600160801b03909316885260208801919091526040870152606086015250929695505050505050565b604080516080810182525f808252602082018190528183018190526060820181905261012d5492516306fa80b360e31b81526004810186905260248101859052919290918291829182916001600160a01b0316906337d4059890604401608060405180830381865afa158015613443573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906134679190615813565b9288526001600160801b039091166020880152151560408701526060860152509295945050505050565b5f818152600183016020526040812054801561356b575f6134b3600183615958565b85549091505f906134c690600190615958565b9050808214613525575f865f0182815481106134e4576134e46157c5565b905f5260205f200154905080875f018481548110613504576135046157c5565b5f918252602080832090910192909255918252600188019052604090208390555b855486908061353657613536615e7c565b600190038181905f5260205f20015f90559055856001015f8681526020019081526020015f205f9055600193505050506108de565b5f9150506108de565b5092915050565b5f825f018281548110613590576135906157c5565b905f5260205f200154905092915050565b5f54610100900460ff1661360b5760405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b6064820152608401610a86565b61189533612c81565b5f81815260018301602052604081205461365957508154600181810184555f8481526020808220909301849055845484825282860190935260409020919091556108de565b505f6108de565b6080820151602083015183515f9283928392101561369e57855160208701516136899190615958565b915081866080015161369b9190615958565b90505b85606001518187604001516136b3919061596b565b11156136d057856040015186606001516136cd9190615958565b90505b5f6136dc89898c613a4a565b61012d546040516370be202d60e11b81526001600160a01b038d81166004830152602482018d905260448201879052606482018690529293505f929091169063e17c405a906084015f60405180830381865afa15801561373e573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526137659190810190615708565b90505f5b815181108015613780575088606001518960400151105b156137e9576137b58c8c8c85858151811061379d5761379d6157c5565b602002602001015160400151878d8f60400151613ac1565b604089018051906137c58261586a565b9052508851896137d48261586a565b905250806137e18161586a565b915050613769565b5080518489608001516137fc9190615958565b6138069190615958565b8851899061381590839061596b565b9052505050506040850151945194989497509395505050505050565b60606108de6001600160a01b03831660145b60605f613851836002615e90565b61385c90600261596b565b67ffffffffffffffff81111561387457613874614d1b565b6040519080825280601f01601f19166020018201604052801561389e576020820181803683370190505b509050600360fc1b815f815181106138b8576138b86157c5565b60200101906001600160f81b03191690815f1a905350600f60fb1b816001815181106138e6576138e66157c5565b60200101906001600160f81b03191690815f1a9053505f613908846002615e90565b61391390600161596b565b90505b6001811115613997577f303132333435363738396162636465660000000000000000000000000000000085600f1660108110613954576139546157c5565b1a60f81b82828151811061396a5761396a6157c5565b60200101906001600160f81b03191690815f1a90535060049490941c9361399081615ea7565b9050613916565b5083156114505760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e746044820152606401610a86565b6139ef816131d1565b6040516001600160a01b038216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b905f90a250565b60606114508383604051806060016040528060278152602001615efa60279139613b10565b613aaa6040518061014001604052805f6001600160a01b031681526020015f60020b815260200160608152602001606081526020015f60ff1681526020015f60ff1681526020015f81526020015f81526020015f81526020015f81525090565b613ab48484613b84565b9050611450828483613c49565b8360e881901c60d082901c600180841614613ae286868c8c8b888888613c86565b613af2868685858b5f0151613eb0565b613b0386868c8b8f8c898989613f79565b5050505050505050505050565b60605f80856001600160a01b031685604051613b2c9190615ebc565b5f60405180830381855af49150503d805f8114613b64576040519150601f19603f3d011682016040523d82523d5f602084013e613b69565b606091505b5091509150613b7a86838387614313565b9695505050505050565b613be46040518061014001604052805f6001600160a01b031681526020015f60020b815260200160608152602001606081526020015f60ff1681526020015f60ff1681526020015f81526020015f81526020015f81526020015f81525090565b61012e54613bfb906001600160a01b031684612953565b505060020b60208301526001600160a01b031681528151613c1b90612dcd565b60ff16608083015260408201526020820151613c3690612dcd565b60ff1660a0830152606082015292915050565b5f80613c558585614393565b60208083015160c087015260409283015160e087015281015161010086015201516101209093019290925250505050565b85888881518110613c9957613c996157c5565b60209081029190910101515284518851899089908110613cbb57613cbb6157c5565b6020026020010151604001906001600160a01b031690816001600160a01b0316815250508460200151888881518110613cf657613cf66157c5565b6020026020010151606001906001600160a01b031690816001600160a01b0316815250508360400151888881518110613d3157613d316157c5565b6020026020010151608001819052508360600151888881518110613d5757613d576157c5565b602002602001015160a001819052508360800151888881518110613d7d57613d7d6157c5565b602002602001015160c0019060ff16908160ff16815250508360a00151888881518110613dac57613dac6157c5565b602002602001015160e0019060ff16908160ff168152505080888881518110613dd757613dd76157c5565b602002602001015161010001901515908115158152505082888881518110613e0157613e016157c5565b6020026020010151610120019060020b908160020b8152505081888881518110613e2d57613e2d6157c5565b6020026020010151610140019060020b908160020b815250508360200151888881518110613e5d57613e5d6157c5565b6020026020010151610160019060020b908160020b815250508460600151888881518110613e8d57613e8d6157c5565b6020026020010151610180019060020b908160020b815250505050505050505050565b5f613eba8461450a565b90505f613ec68461450a565b905082878781518110613edb57613edb6157c5565b60200260200101516101a001906001600160a01b031690816001600160a01b03168152505081878781518110613f1357613f136157c5565b60200260200101516101c001906001600160a01b031690816001600160a01b03168152505080878781518110613f4b57613f4b6157c5565b60200260200101516101e001906001600160a01b031690816001600160a01b03168152505050505050505050565b61012d546040516307c9b93f60e21b815260048101899052602481018890526001600160a01b0387811660448301525f921690631f26e4fc90606401608060405180830381865afa158015613fd0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613ff491906157d9565b505061012d546040516306fa80b360e31b8152600481018c9052602481018b90529293505f926001600160a01b0390911691506337d4059890604401608060405180830381865afa15801561404b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061406f9190615813565b5092505050818b8b81518110614087576140876157c5565b602002602001015161020001906001600160801b031690816001600160801b031681525050878b8b815181106140bf576140bf6157c5565b602002602001015160200181815250508560c001518b8b815181106140e6576140e66157c5565b60200260200101516102a00181815250508561010001518b8b8151811061410f5761410f6157c5565b60200260200101516102c00181815250508560e001518b8b81518110614137576141376157c5565b60200260200101516102e00181815250508561012001518b8b81518110614160576141606157c5565b60200260200101516103000181815250505f61417d888b8b611457565b9050805f01518c8c81518110614195576141956157c5565b602002602001015161022001818152505080602001518c8c815181106141bd576141bd6157c5565b602002602001015161024001818152505080604001518c8c815181106141e5576141e56157c5565b602002602001015161026001818152505080606001518c8c8151811061420d5761420d6157c5565b602002602001015161028001818152505061422c8c8c888887896147cf565b81158c8c81518110614240576142406157c5565b60200260200101516103800190151590811515815250505f8c8c8151811061426a5761426a6157c5565b60200260200101516101c0015190505f8d8d8151811061428c5761428c6157c5565b60200260200101516101e00151905085156142d4576142ac8282876148a1565b8e8e815181106142be576142be6157c5565b6020026020010151610360018181525050614303565b6142df82828761491c565b8e8e815181106142f1576142f16157c5565b60200260200101516103600181815250505b5050505050505050505050505050565b606083156143815782515f0361437a576001600160a01b0385163b61437a5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610a86565b508161438b565b61438b838361496e565b949350505050565b6143bd60405180606001604052805f6001600160a01b031681526020015f81526020015f81525090565b6143e760405180606001604052805f6001600160a01b031681526020015f81526020015f81525090565b60a083205f9084516001600160a01b03908116855260208601518116845261012d546040516370be202d60e11b81528883166004820152602481018490525f604482018190526064820181905293945091169063e17c405a906084015f60405180830381865afa15801561445d573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526144849190810190615708565b90505f5b8151811015614500575f6144ba88858585815181106144a9576144a96157c5565b602002602001015160400151611457565b8051602080890180519092019091528082015190870180519091019052604080820151818901805190910190526060909101519086018051909101905250600101614488565b5050509250929050565b60020b5f60ff82901d80830118620d89e8811115614533576145336345c3193d60e11b84614998565b7001fffcb933bd6fad37aa2d162d1a594001600182160270010000000000000000000000000000000018600282161561457c576ffff97272373d413259a46990580e213a0260801c5b600482161561459b576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b60088216156145ba576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b60108216156145d9576fffcb9843d60f6159c9db58835c9266440260801c5b60208216156145f8576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615614617576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615614636576ffe5dee046a99a2a811c461f1969c30530260801c5b610100821615614656576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615614676576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615614696576ff3392b0822b70005940c7a398e4b70f30260801c5b6108008216156146b6576fe7159475a2c29b7443b29c7fa6e889d90260801c5b6110008216156146d6576fd097f3bdfd2022b8845ad8f792aa58250260801c5b6120008216156146f6576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615614716576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615614736576f31be135f97d08fd981231505542fcfa60260801c5b62010000821615614757576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b62020000821615614777576e5d6af8dedb81196699c329225ee6040260801c5b62040000821615614796576d2216e584f5fa1ea926041bedfe980260801c5b620800008216156147b3576b048a170391f7dc42444e8fa20260801c5b5f8413156147bf575f19045b63ffffffff0160201c9392505050565b5f6147d98561450a565b90505f6147e58561450a565b90508215614844575f888881518110614800576148006157c5565b602002602001015161032001818152505061481c82828661491c565b88888151811061482e5761482e6157c5565b6020026020010151610340018181525050614897565b61484f8282866148a1565b888881518110614861576148616157c5565b60200260200101516103200181815250505f888881518110614885576148856157c5565b60200260200101516103400181815250505b5050505050505050565b5f826001600160a01b0316846001600160a01b031611156148c0579192915b6001600160a01b0384166149127bffffffffffffffffffffffffffffffff000000000000000000000000606085901b166148fa8787615ec7565b6001600160a01b0316866001600160a01b03166149a7565b61438b9190615ee6565b5f826001600160a01b0316846001600160a01b0316111561493b579192915b61438b6001600160801b0383166149528686615ec7565b6001600160a01b03166c010000000000000000000000006149a7565b81511561497e5781518083602001fd5b8060405162461bcd60e51b8152600401610a869190615e6a565b815f528060020b60045260245ffd5b5f838302815f19858709828110838203039150508084116149c6575f80fd5b805f036149d857508290049050611450565b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b604080516103a0810182525f8082526020820181905291810182905260608082018390526080820181905260a082015260c0810182905260e08101829052610100810182905261012081018290526101408101829052610160810182905261018081018290526101a081018290526101c081018290526101e08101829052610200810182905261022081018290526102408101829052610260810182905261028081018290526102a081018290526102c081018290526102e08101829052610300810182905261032081018290526103408101829052610360810182905261038081019190915290565b5f60208284031215614b3d575f80fd5b81356001600160e01b031981168114611450575f80fd5b62ffffff81168114610c14575f80fd5b5f8060408385031215614b75575f80fd5b823591506020830135614b8781614b54565b809150509250929050565b5f606082018560020b83526001600160a01b0385166020840152606060408401528084518083526080850191506020860192505f5b81811015614c21578351805160020b84526001600160a01b0360208201511660208501526040810151604085015260608101516060850152608081015160808501525060a083019250602084019350600181019050614bc7565b5090979650505050505050565b5f60208284031215614c3e575f80fd5b5035919050565b6001600160a01b0381168114610c14575f80fd5b5f8060408385031215614c6a575f80fd5b823591506020830135614b8781614c45565b5f60208284031215614c8c575f80fd5b813561145081614c45565b5f805f8060808587031215614caa575f80fd5b8435614cb581614c45565b966020860135965060408601359560600135945092505050565b604080825283519082018190525f9060208501906060840190835b81811015614d08578351835260209384019390920191600101614cea565b5050602093909301939093525092915050565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff81118282101715614d5257614d52614d1b565b60405290565b6040516060810167ffffffffffffffff81118282101715614d5257614d52614d1b565b6040516080810167ffffffffffffffff81118282101715614d5257614d52614d1b565b604051601f8201601f1916810167ffffffffffffffff81118282101715614dc757614dc7614d1b565b604052919050565b5f67ffffffffffffffff821115614de857614de8614d1b565b50601f01601f191660200190565b5f8060408385031215614e07575f80fd5b8235614e1281614c45565b9150602083013567ffffffffffffffff811115614e2d575f80fd5b8301601f81018513614e3d575f80fd5b8035614e50614e4b82614dcf565b614d9e565b818152866020838501011115614e64575f80fd5b816020840160208301375f602083830101528093505050509250929050565b8015158114610c14575f80fd5b5f8060408385031215614ea1575f80fd5b823591506020830135614b8781614e83565b5f805f60608486031215614ec5575f80fd5b505081359360208301359350604090920135919050565b602080825282518282018190525f918401906040840190835b81811015614f13578351835260209384019390920191600101614ef5565b509095945050505050565b5f805f60608486031215614f30575f80fd5b8335614f3b81614c45565b95602085013595506040909401359392505050565b5f8060408385031215614f61575f80fd5b8235614f6c81614c45565b946020939093013593505050565b602080825282518282018190525f918401906040840190835b81811015614f135783516001600160801b038151168452602081015160208501526040810151604085015250606083019250602084019350600181019050614f93565b5f60a08284031215614fe6575f80fd5b50919050565b5f60a08284031215614ffc575f80fd5b6114508383614fd6565b8060020b8114610c14575f80fd5b5f805f805f805f60e0888a03121561502a575f80fd5b87359650602088013561503c81614e83565b9550604088013561504c81615006565b9450606088013561505c81615006565b9699959850939660808101359560a0820135955060c0909101359350915050565b602080825282518282018190525f918401906040840190835b81811015614f13578351805160020b8452602081015160020b60208501526040810151604085015250606083019250602084019350600181019050615096565b602080825282518282018190525f918401906040840190835b81811015614f135783518051845260209081015181850152909301926040909201916001016150ef565b5f8060c0838503121561512a575f80fd5b8235915061513b8460208501614fd6565b90509250929050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b5f602082016020835280845180835260408501915060408160051b8601019250602086015f5b8281101561525d57603f19878603018452815180518652602081015161520f60208801826001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b50604081015161010060c088015261522b610100880182615144565b90506060820151915086810360e08801526152468183615144565b965050506020938401939190910190600101615198565b50929695505050505050565b5f604082016040835280855180835260608501915060608160051b8601019250602087015f5b828110156154de57605f198786030184528151805186526020810151602087015260408101516152ca60408801826001600160a01b03169052565b5060608101516152e560608801826001600160a01b03169052565b5060808101516103a060808801526153016103a0880182615144565b905060a082015187820360a089015261531a8282615144565b91505060c082015161533160c089018260ff169052565b5060e082015161534660e089018260ff169052565b5061010082015161535c61010089018215159052565b5061012082015161537361012089018260020b9052565b5061014082015161538a61014089018260020b9052565b506101608201516153a161016089018260020b9052565b506101808201516153b861018089018260020b9052565b506101a08201516153d56101a08901826001600160a01b03169052565b506101c08201516153f26101c08901826001600160a01b03169052565b506101e082015161540f6101e08901826001600160a01b03169052565b5061020082015161542c6102008901826001600160801b03169052565b506102208201516102208801526102408201516102408801526102608201516102608801526102808201516102808801526102a08201516102a08801526102c08201516102c08801526102e08201516102e088015261030082015161030088015261032082015161032088015261034082015161034088015261036082015161036088015261038082015191506154c861038088018315159052565b955050602093840193919091019060010161528f565b505050506020929092019290925292915050565b5f805f60608486031215615504575f80fd5b83359250602084013561551681615006565b9150604084013561552681615006565b809150509250925092565b6001600160a01b03851681526020810184905261010081016155a460408301856001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b62ffffff831660e083015295945050505050565b5f67ffffffffffffffff8211156155d1576155d1614d1b565b5060051b60200190565b5f805f606084860312156155ed575f80fd5b83516155f881615006565b602085015190935061560981614c45565b604085015190925067ffffffffffffffff811115615625575f80fd5b8401601f81018613615635575f80fd5b8051615643614e4b826155b8565b80828252602082019150602060a08402850101925088831115615664575f80fd5b6020840193505b828410156156df5760a0848a031215615682575f80fd5b61568a614d2f565b845161569581615006565b815260208501516156a581614c45565b60208281019190915260408681015190830152606080870151908301526080808701519083015290835260a090940193919091019061566b565b809450505050509250925092565b80516001600160801b0381168114615703575f80fd5b919050565b5f60208284031215615718575f80fd5b815167ffffffffffffffff81111561572e575f80fd5b8201601f8101841361573e575f80fd5b805161574c614e4b826155b8565b8082825260208201915060206060840285010192508683111561576d575f80fd5b6020840193505b82841015613b7a576060848803121561578b575f80fd5b615793614d58565b61579c856156ed565b815260208581015181830152604080870151908301529083526060909401939190910190615774565b634e487b7160e01b5f52603260045260245ffd5b5f805f80608085870312156157ec575f80fd5b6157f5856156ed565b60208601516040870151606090970151919890975090945092505050565b5f805f8060808587031215615826575f80fd5b84519350615836602086016156ed565b9250604085015161584681614e83565b6060959095015193969295505050565b634e487b7160e01b5f52601160045260245ffd5b5f6001820161587b5761587b615856565b5060010190565b600281810b9083900b01627fffff8113627fffff19821217156108de576108de615856565b634e487b7160e01b5f52601260045260245ffd5b5f8260020b806158cd576158cd6158a7565b808360020b0791505092915050565b5f8160020b8360020b806158f2576158f26158a7565b627fffff1982145f198214161561590b5761590b615856565b90059392505050565b5f8260020b8260020b028060020b915080821461357457613574615856565b600282810b9082900b03627fffff198112627fffff821317156108de576108de615856565b818103818111156108de576108de615856565b808201808211156108de576108de615856565b5f6020828403121561598e575f80fd5b5051919050565b825180516001600160801b03168252602080820151908301526040808201519083015260609081015190820152610200810160208481015180516080850152908101516001600160801b031660a08401526040810151151560c0840152606081015160e08401525060408401516001600160a01b0381166101008401525060608401516101208301526080840151615a3361014084018260020b9052565b5060a0840151615a4961016084018260020b9052565b5060c0840151151561018083015260e08401516101a08301526101008401516101c08301526001600160a01b0383166101e0830152611450565b5f6080828403128015615a94575f80fd5b50615a9d614d7b565b8251815260208084015190820152604080840151908201526060928301519281019290925250919050565b5f60a0828403128015615ad9575f80fd5b50615ae2614d2f565b8235615aed81614c45565b81526020830135615afd81614c45565b60208201526040830135615b1081614b54565b60408201526060830135615b2381615006565b60608201526080830135615b3681614c45565b60808201529392505050565b5f60208284031215615b52575f80fd5b815161145081614b54565b5f60208284031215615b6d575f80fd5b815167ffffffffffffffff811115615b83575f80fd5b8201601f81018413615b93575f80fd5b8051615ba1614e4b826155b8565b8082825260208201915060208360071b850101925086831115615bc2575f80fd5b6020840193505b82841015613b7a5760808488031215615be0575f80fd5b615be8614d7b565b8451615bf381615006565b81526020850151615c0381615006565b602082015260408581015190820152615c1e606086016156ed565b6060820152825260809390930192602090910190615bc9565b5f60208284031215615c47575f80fd5b815161145081614c45565b8135615c5d81614c45565b81546001600160a01b0319166001600160a01b03821617825550600181016020830135615c8981614c45565b81546001600160a01b0319166001600160a01b038216178255506040830135615cb181614b54565b81546060850135615cc181615006565b8060b81b79ffffff00000000000000000000000000000000000000000000001676ffffff00000000000000000000000000000000000000008460a01b167fffffffffffff000000000000ffffffffffffffffffffffffffffffffffffffff841617178455505050505f6080830135615d3881614c45565b6002830180546001600160a01b0319166001600160a01b03831617905590508061228f565b5f60208284031215615d6d575f80fd5b815167ffffffffffffffff811115615d83575f80fd5b8201601f81018413615d93575f80fd5b8051615da1614e4b82614dcf565b818152856020838501011115615db5575f80fd5b8160208401602083015e5f91810160200191909152949350505050565b5f60208284031215615de2575f80fd5b815160ff81168114611450575f80fd5b5f81518060208401855e5f93019283525090919050565b7f416363657373436f6e74726f6c3a206163636f756e742000000000000000000081525f615e3a6017830185615df2565b7f206973206d697373696e6720726f6c652000000000000000000000000000000081526115116011820185615df2565b602081525f6114506020830184615144565b634e487b7160e01b5f52603160045260245ffd5b80820281158282048414176108de576108de615856565b5f81615eb557615eb5615856565b505f190190565b5f6114508284615df2565b6001600160a01b0382811682821603908111156108de576108de615856565b5f82615ef457615ef46158a7565b50049056fe416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564a26469706673582212206ec2968168f07aa654128914d5e1b84f57f31e85718e7036dfbd4972dc07a90464736f6c634300081a0033
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
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.