Verified contractPartialUNLICENSED
PositionFeeModule
Address0xf211ebf0662fa313b68ba78adb257a0b1d555f52
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 1 runs
- EVM version
- cancun
- Via IR
- yes
- License
- UNLICENSED
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,333,783
- Creation transaction
- 0x89d30affac…e8cac00696
40 files
- contracts/module/PositionFeeModule.solmain17.19 KB
- contracts/module/BytesUtils.sol6.87 KB
- contracts/module/base/SafeModuleBase.sol24.88 KB
- contracts/module/interfaces/IPositionFeeModule.sol5.11 KB
- contracts/module/interfaces/ISafe.sol2.74 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol4.93 KB
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol3.38 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
- lib/v4-core/src/interfaces/IExtsload.sol1.02 KB
- lib/v4-core/src/interfaces/IExttload.sol699 B
- lib/v4-core/src/interfaces/IHooks.sol8.23 KB
- lib/v4-core/src/interfaces/IPoolManager.sol12.84 KB
- lib/v4-core/src/interfaces/IProtocolFees.sol2.49 KB
- lib/v4-core/src/interfaces/external/IERC20Minimal.sol3.04 KB
- lib/v4-core/src/interfaces/external/IERC6909Claims.sol3.16 KB
- lib/v4-core/src/libraries/CustomRevert.sol5.17 KB
- lib/v4-core/src/libraries/Hooks.sol16.51 KB
- lib/v4-core/src/libraries/LPFeeLibrary.sol3.6 KB
- lib/v4-core/src/libraries/ParseBytes.sol1.2 KB
- lib/v4-core/src/libraries/SafeCast.sol2.27 KB
- lib/v4-core/src/types/BalanceDelta.sol2.34 KB
- lib/v4-core/src/types/BeforeSwapDelta.sol1.47 KB
- lib/v4-core/src/types/Currency.sol5.46 KB
- lib/v4-core/src/types/PoolId.sol539 B
- lib/v4-core/src/types/PoolKey.sol805 B
- lib/v4-core/src/types/PoolOperation.sol907 B
- lib/v4-periphery/lib/permit2/src/interfaces/IAllowanceTransfer.sol7.7 KB
- lib/v4-periphery/lib/permit2/src/interfaces/IEIP712.sol144 B
- lib/v4-periphery/src/interfaces/IEIP712_v4.sol328 B
- lib/v4-periphery/src/interfaces/IERC721Permit_v4.sol2.14 KB
- lib/v4-periphery/src/interfaces/IImmutableState.sol365 B
- lib/v4-periphery/src/interfaces/IMulticall_v4.sol774 B
- lib/v4-periphery/src/interfaces/INotifier.sol3.2 KB
- lib/v4-periphery/src/interfaces/IPermit2Forwarder.sol1.44 KB
- lib/v4-periphery/src/interfaces/IPoolInitializer_v4.sol782 B
- lib/v4-periphery/src/interfaces/IPositionManager.sol3.5 KB
- lib/v4-periphery/src/interfaces/ISubscriber.sol2.27 KB
- lib/v4-periphery/src/interfaces/IUnorderedNonce.sol799 B
- lib/v4-periphery/src/libraries/PositionInfoLibrary.sol3.95 KB
contracts/module/PositionFeeModule.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;
import {BytesUtils} from "./BytesUtils.sol";
import {ISafe} from "./interfaces/ISafe.sol";
import {IPositionFeeModule} from "./interfaces/IPositionFeeModule.sol";
import {SafeModuleBase} from "./base/SafeModuleBase.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {IPositionManager} from "@uniswap/v4-periphery/src/interfaces/IPositionManager.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "@uniswap/v4-core/src/types/PoolId.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";
/**
* @title PositionFeeModule
* @author Manifest Finance
* @notice Safe Module that lets an authorized bot collect Uniswap V4 LP fees; this module builds
* no payload other than a collect. A collect still fires the pinned pool's
* beforeRemoveLiquidity hook callback, because V4 routes any liquidityDelta <= 0 to the
* remove callbacks, so it is not read-only from the pool's perspective.
* @dev WHY TYPED ARGUMENTS AND NOT A SELECTOR ALLOWLIST: a V4 liquidity operation's semantics live
* in its bytes argument, never in the selector. modifyLiquidities(bytes,uint256) = 0xdd46508f
* carries BURN_POSITION, SWEEP, a full-principal DECREASE_LIQUIDITY, TAKE to an arbitrary
* recipient, and SETTLE with a Permit2 pull, all under that one selector, and
* modifyLiquiditiesWithoutUnlock reaches the same action vocabulary under another selector
* (with actions and params as two top-level arguments rather than one encoded blob, so the
* layouts differ even though the reachable operations do not). A collect and a total exit
* differ in exactly one word (`liquidity`, offset 0x20 of params[0]), which no selector check
* can see. So the bot supplies one integer and this module writes every byte.
*
* WHY SAFE AND POOL ARE IMMUTABLE: CLOSE_CURRENCY is only provably a credit for a hook that
* does not enable afterRemoveLiquidityReturnDelta. A hook that does can turn a zero-liquidity
* decrease into a debit, which CLOSE_CURRENCY would then settle FROM the Safe. Pinning the pool
* keeps the safety argument and the authorization in the same scope.
*
* LAYOUT OF THE PAYLOAD THIS MODULE BUILDS:
* actions = 0x01 0x12 0x12 DECREASE_LIQUIDITY, CLOSE_CURRENCY, CLOSE_CURRENCY
* params[0] = (tokenId, 0, 0, 0, "") <- the 0 in slot 1 is what makes this a collect
* params[1] = (currency0)
* params[2] = (currency1)
*/
contract PositionFeeModule is IPositionFeeModule, SafeModuleBase {
using BytesUtils for bytes;
using PoolIdLibrary for PoolKey;
/// @notice Timelock opType for allowlist additions. Base reserves 1.
uint8 public constant OP_ADD_TOKEN_ID = 2;
/// @dev Uniswap v4 action codes, redeclared locally so this module pulls in no periphery
/// library for two constants.
uint8 private constant ACTION_DECREASE_LIQUIDITY = 0x01;
uint8 private constant ACTION_CLOSE_CURRENCY = 0x12;
/// @notice The Uniswap V4 PositionManager this module calls, and the ERC721 holding the positions
IPositionManager public immutable POSITION_MANAGER;
/// @notice The only Safe this module executes through, and the only address a collect can credit
address public immutable SAFE;
/// @notice The only pool a collectable position may belong to. Re-checked on every collect
PoolId public immutable EXPECTED_POOL_ID;
/// @notice Whether the bot may collect from this position id
mapping(uint256 => bool) public isCollectable;
uint256[] private _tokenIds;
/// @notice Deploys the module pinned to one Safe, one PositionManager and one pool.
/// @param _positionManager The Uniswap V4 PositionManager holding the positions
/// @param _safe The Safe that owns the positions and receives every collected fee
/// @param _expectedPoolId The only pool whose positions this module will ever touch
/// @param _authorizedBot The single address allowed to call executeCollectFees. Not constrained
/// to an EOA; any address works
/// @param _owner The address allowed to administer the allowlist, the bot and the pause
/// @param _timelockDelay Seconds EVERY timelocked operation waits, allowlist additions and
/// authorized-bot rotations alike. 0 selects DEFAULT_TIMELOCK_DELAY; above
/// TIMELOCK_EXPIRY reverts TimelockDelayExceedsExpiry
/// @param _initialTokenIds Seed allowlist, pool-checked id by id. Must be non-empty: the FIRST
/// entry's PoolKey is what the constructor uses to check the currencies and the hook
/// flag, and the matching pool id makes that key stand for all of them
constructor(
address _positionManager,
address _safe,
PoolId _expectedPoolId,
address _authorizedBot,
address _owner,
uint256 _timelockDelay,
uint256[] memory _initialTokenIds
) SafeModuleBase(_authorizedBot, _owner, _timelockDelay) {
if (_positionManager == address(0)) revert InvalidAddress();
if (_safe == address(0)) revert InvalidAddress();
POSITION_MANAGER = IPositionManager(_positionManager);
SAFE = _safe;
EXPECTED_POOL_ID = _expectedPoolId;
// At least one seed id is required: EXPECTED_POOL_ID is a hash, and a position living in
// that pool is how this constructor gets the PoolKey behind it to check the currencies and
// the hook flag below.
if (_initialTokenIds.length == 0) revert NoInitialTokenIds();
// Every seed id is pool-validated here, inside the loop, rather than only the first: this
// allowlist write is the one path that has no timelock behind it, so it must not be able to
// seed a foreign-pool id just because the FIRST id in the array happens to be correct.
PoolKey memory seedKey;
for (uint256 i; i < _initialTokenIds.length;) {
uint256 seedId = _initialTokenIds[i];
(PoolKey memory candidateKey,) = POSITION_MANAGER.getPoolAndPositionInfo(seedId);
if (PoolId.unwrap(candidateKey.toId()) != PoolId.unwrap(_expectedPoolId)) {
revert UnexpectedPool(seedId);
}
if (i == 0) {
seedKey = candidateKey;
}
_addTokenId(seedId);
unchecked {
++i;
}
}
// Validate both legs are ERC20 once, here, using the first seed's key: a matching pool id
// implies identical currencies (and hook, below), because PoolId is the keccak of the whole
// PoolKey. The emitted amounts are ERC20 balance deltas and would be wrong for a native leg.
if (seedKey.currency0.isAddressZero() || seedKey.currency1.isAddressZero()) {
revert NativeCurrencyUnsupported();
}
// _collect's fund-safety argument is that CLOSE_CURRENCY can only ever credit the Safe. That
// is only true for a hook that cannot turn the zero-liquidity DECREASE_LIQUIDITY this module
// issues into a debit. A hook with afterRemoveLiquidityReturnDelta enabled can do exactly
// that, and CLOSE_CURRENCY would then settle FROM the Safe via Permit2. Checked once here,
// against the real Hooks permission bit (encoded in the hook address), rather than trusted to
// deployment-time discipline.
if (Hooks.hasPermission(seedKey.hooks, Hooks.AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)) {
revert HookMayReturnRemoveDelta();
}
emit PositionFeeModuleInitialized(_positionManager, _safe, _authorizedBot);
}
// ========================================
// ALLOWLIST
// ========================================
/// @notice Queues a timelocked addition to the collectable allowlist. The position does not
/// become collectable until executeAddTokenId runs.
/// @dev Two guards together keep removeTokenId from being undone by a leftover queue without a
/// newly announced delay, and neither is sufficient alone: the isCollectable check below
/// refuses an id that is collectable right now, and the base refuses a second live add of
/// the same (opType, payload). The first admits two queues while the id is inactive, and
/// the base frees its slot the moment one of them executes. Pool and ownership are not
/// checked here; they are checked on every collect, so a queued id that fails them is inert.
/// @param tokenId The position to make collectable once the timelock elapses
/// @return operationId Handle for executeAddTokenId or cancelTimelock. Retain it: it is derived
/// from an internal nonce and the queueing context, not from tokenId
function queueAddTokenId(uint256 tokenId) external onlyOwner returns (bytes32 operationId) {
if (isCollectable[tokenId]) revert TokenIdAlreadyCollectable(tokenId);
operationId = _queue(OP_ADD_TOKEN_ID, keccak256(abi.encode(tokenId)));
}
/// @notice Applies a queued allowlist addition once its delay has elapsed.
/// @dev tokenId must be identical to the one queued; it is rebound against the stored payload
/// hash and a mismatch reverts TimelockPayloadMismatch.
/// @param operationId The handle returned by queueAddTokenId
/// @param tokenId The same position id that was queued
function executeAddTokenId(bytes32 operationId, uint256 tokenId) external onlyOwner {
_consume(operationId, OP_ADD_TOKEN_ID, keccak256(abi.encode(tokenId)));
_addTokenId(tokenId);
}
/// @notice Removes a position from the collectable allowlist, immediately.
/// @dev Deliberately outside the timelock: narrowing what the bot may touch must not wait.
/// Adding is the direction that waits. No live add for this tokenId can exist when this
/// call succeeds, because queueAddTokenId refuses an id that is already collectable and
/// the base refuses a second live add of the same id, so re-widening after this call
/// always starts a new delay.
/// @param tokenId The position to stop the bot collecting from
function removeTokenId(uint256 tokenId) external onlyOwner {
if (!isCollectable[tokenId]) revert TokenIdNotCollectable(tokenId);
isCollectable[tokenId] = false;
uint256 len = _tokenIds.length;
for (uint256 i; i < len;) {
if (_tokenIds[i] == tokenId) {
_tokenIds[i] = _tokenIds[len - 1];
_tokenIds.pop();
break;
}
unchecked {
++i;
}
}
emit TokenIdRemoved(tokenId);
}
/// @notice Returns every position id currently on the collectable allowlist.
/// @dev Enumerable rather than a bare mapping so an off-chain reader need not keep a duplicate
/// list in config and drift from it. Order is not stable: removeTokenId swap-and-pops.
/// @return The collectable position ids, in no meaningful order
function getCollectableTokenIds() external view returns (uint256[] memory) {
return _tokenIds;
}
// ========================================
// EXECUTION
// ========================================
/// @notice Collects accrued LP fees from an allowlisted position into the pinned Safe. Moves no
/// principal: the DECREASE_LIQUIDITY this builds carries liquidity = 0.
/// @dev Callable only by the authorized bot, only while unpaused, and non-reentrant.
/// This module's own guards reject the call unless the position is allowlisted, the Safe
/// still has this module enabled, the Safe still owns the position, the position still
/// belongs to EXPECTED_POOL_ID, and it holds liquidity. Passing all of them is not a
/// guarantee of success: the call then goes through the Safe to the PositionManager and
/// into the pinned pool's hook, any of which can revert for its own reasons, and those
/// reverts surface wrapped in the module's revert string.
/// Where it does succeed, a position with no accrued fees is a no-op that emits zeros.
/// @param tokenId The allowlisted position to collect from
function executeCollectFees(uint256 tokenId) external onlyAuthorizedBot notPaused nonReentrant {
if (!isCollectable[tokenId]) revert TokenIdNotCollectable(tokenId);
if (!ISafe(SAFE).isModuleEnabled(address(this))) revert ModuleNotEnabled();
if (IERC721(address(POSITION_MANAGER)).ownerOf(tokenId) != SAFE) {
revert PositionNotOwnedBySafe(tokenId);
}
(PoolKey memory key,) = POSITION_MANAGER.getPoolAndPositionInfo(tokenId);
if (PoolId.unwrap(key.toId()) != PoolId.unwrap(EXPECTED_POOL_ID)) revert UnexpectedPool(tokenId);
if (POSITION_MANAGER.getPositionLiquidity(tokenId) == 0) revert PositionEmpty(tokenId);
_collect(tokenId, key);
}
// ========================================
// VIEWS
// ========================================
/// @notice Human-readable version of this module's source.
/// @return The version string, currently "PositionFeeModule v1.0.0"
function getVersion() external pure returns (string memory) {
return "PositionFeeModule v1.0.0";
}
// ========================================
// INTERNAL
// ========================================
/// @dev The duplicate guard below is reachable only from the constructor's seed loop, the one
/// path that writes the allowlist with no timelock in front of it. executeAddTokenId cannot
/// arrive here with a collectable id: queueAddTokenId refuses one, and the base allows a
/// single live add per id. Relaxing either makes this branch reachable from execute again.
function _addTokenId(uint256 tokenId) internal {
if (isCollectable[tokenId]) revert TokenIdAlreadyCollectable(tokenId);
isCollectable[tokenId] = true;
_tokenIds.push(tokenId);
emit TokenIdAdded(tokenId);
}
/**
* @dev Builds and executes the collect. Every byte handed to the PositionManager originates
* here; the bot contributes only `tokenId`, and the currencies come from the position
* itself rather than from any caller.
*
* amount0Min / amount1Min are 0 and the slippage check is vacuous rather than skipped:
* PositionManager validates the PRINCIPAL delta, total minus fees accrued, which is exactly
* zero for a zero-liquidity decrease. Nonzero minimums would matter only for a nonzero
* decrease, which this module never builds.
*
* deadline = block.timestamp is correct: PositionManager's checkDeadline modifier reverts
* only on `block.timestamp > deadline`, so equality passes, and module and Safe execute in
* the same transaction, so there is no signed-payload replay window to protect.
*/
function _collect(uint256 tokenId, PoolKey memory key) internal {
IERC20 token0 = IERC20(Currency.unwrap(key.currency0));
IERC20 token1 = IERC20(Currency.unwrap(key.currency1));
uint256 before0 = token0.balanceOf(SAFE);
uint256 before1 = token1.balanceOf(SAFE);
bytes memory actions = abi.encodePacked(ACTION_DECREASE_LIQUIDITY, ACTION_CLOSE_CURRENCY, ACTION_CLOSE_CURRENCY);
bytes[] memory params = new bytes[](3);
params[0] = abi.encode(tokenId, uint256(0), uint128(0), uint128(0), bytes(""));
params[1] = abi.encode(key.currency0);
params[2] = abi.encode(key.currency1);
bytes memory callData =
abi.encodeCall(IPositionManager.modifyLiquidities, (abi.encode(actions, params), block.timestamp));
(bool success, bytes memory returnData) = ISafe(SAFE)
.execTransactionFromModuleReturnData(address(POSITION_MANAGER), 0, callData, ISafe.Operation.Call);
if (!success) {
returnData.revertWithError("PositionFeeModule: collect failed: ");
}
// These are the Safe's measured balance credit across the call. They equal the position's
// gross accrued fees only while neither leg of the pinned pool is fee-on-transfer and
// nothing else credits the Safe mid-call, and neither is asserted at emit time: the pool's
// remove callback runs synchronously between the snapshot above and the settle, so anything
// it pushed to the Safe lands in these numbers too. The subtraction is checked, so a net
// debit on either leg reverts the whole call; the caveat is about what the event reports,
// not about fund safety.
emit FeesCollected(tokenId, token0.balanceOf(SAFE) - before0, token1.balanceOf(SAFE) - before1);
}
}
contracts/module/BytesUtils.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;
library BytesUtils {
function calldataSliceSelector(bytes calldata _bytes) internal pure returns (bytes4 selector) {
selector = _bytes[0] | (bytes4(_bytes[1]) >> 8) | (bytes4(_bytes[2]) >> 16) | (bytes4(_bytes[3]) >> 24);
}
function memorySliceSelector(bytes memory _bytes) internal pure returns (bytes4 selector) {
selector = _bytes[0] | (bytes4(_bytes[1]) >> 8) | (bytes4(_bytes[2]) >> 16) | (bytes4(_bytes[3]) >> 24);
}
/**
* @notice Parse and revert with a descriptive error message based on return data format
* @dev Handles: empty data, bool, Error(string), Panic(uint256), custom errors, and unknown formats
* @param _bytes The return data to parse
* @param _tracingInfo Prefix to add to the error message for context
*/
function revertWithError(bytes memory _bytes, string memory _tracingInfo) internal pure {
// Handle empty return data (some functions don't return anything)
if (_bytes.length == 0) {
revert(string(abi.encodePacked(_tracingInfo, "transaction failed with no return data")));
}
// Handle boolean/uint256 return (32 bytes) - common for ERC20 transfers
if (_bytes.length == 32) {
bool success;
assembly {
success := mload(add(_bytes, 0x20))
}
if (!success) {
revert(string(abi.encodePacked(_tracingInfo, "transaction returned false")));
} else {
revert(
string(abi.encodePacked(_tracingInfo, "transaction marked failed but returned true (unexpected)"))
);
}
}
// Need at least 4 bytes for a selector
if (_bytes.length >= 4) {
bytes4 selector;
assembly {
selector := mload(add(_bytes, 0x20))
}
// Handle Error(string) format: selector 0x08c379a0
if (selector == 0x08c379a0 && _bytes.length >= 68) {
assembly {
_bytes := add(_bytes, 68)
}
revert(string(abi.encodePacked(_tracingInfo, string(_bytes))));
}
// Handle Panic(uint256) format: selector 0x4e487b71
if (selector == 0x4e487b71 && _bytes.length >= 36) {
uint256 panicCode;
assembly {
panicCode := mload(add(_bytes, 0x24))
}
string memory panicMsg = _getPanicMessage(panicCode);
revert(string(abi.encodePacked(_tracingInfo, "panic: ", panicMsg)));
}
// Handle custom errors - just show the selector
revert(string(abi.encodePacked(_tracingInfo, "custom error 0x", _toHexString(selector))));
}
// Fallback for truly unexpected formats
revert(string(abi.encodePacked(_tracingInfo, "unexpected return data format")));
}
/**
* @notice Parse and return a descriptive error message based on return data format
* @dev Same logic as revertWithError but returns string instead of reverting
* @param _bytes The return data to parse
* @param _tracingInfo Prefix to add to the error message for context
* @return string The parsed error message
*/
function returnError(bytes memory _bytes, string memory _tracingInfo) internal pure returns (string memory) {
// Handle empty return data
if (_bytes.length == 0) {
return string(abi.encodePacked(_tracingInfo, "transaction failed with no return data"));
}
// Handle boolean/uint256 return (32 bytes)
if (_bytes.length == 32) {
bool success;
assembly {
success := mload(add(_bytes, 0x20))
}
if (!success) {
return string(abi.encodePacked(_tracingInfo, "transaction returned false"));
} else {
return
string(abi.encodePacked(_tracingInfo, "transaction marked failed but returned true (unexpected)"));
}
}
// Need at least 4 bytes for a selector
if (_bytes.length >= 4) {
bytes4 selector;
assembly {
selector := mload(add(_bytes, 0x20))
}
// Handle Error(string) format
if (selector == 0x08c379a0 && _bytes.length >= 68) {
assembly {
_bytes := add(_bytes, 68)
}
return string(abi.encodePacked(_tracingInfo, string(_bytes)));
}
// Handle Panic(uint256) format
if (selector == 0x4e487b71 && _bytes.length >= 36) {
uint256 panicCode;
assembly {
panicCode := mload(add(_bytes, 0x24))
}
string memory panicMsg = _getPanicMessage(panicCode);
return string(abi.encodePacked(_tracingInfo, "panic: ", panicMsg));
}
// Handle custom errors
return string(abi.encodePacked(_tracingInfo, "custom error 0x", _toHexString(selector)));
}
// Fallback
return string(abi.encodePacked(_tracingInfo, "unexpected return data format"));
}
/**
* @notice Get human-readable message for Solidity panic codes
* @param code The panic error code
* @return string Description of the panic error
*/
function _getPanicMessage(uint256 code) private pure returns (string memory) {
if (code == 0x00) return "generic/unspecified error";
if (code == 0x01) return "assertion failed";
if (code == 0x11) return "arithmetic underflow or overflow";
if (code == 0x12) return "division or modulo by zero";
if (code == 0x21) return "invalid enum conversion";
if (code == 0x22) return "invalid storage byte array encoding";
if (code == 0x31) return "pop() on empty array";
if (code == 0x32) return "array out of bounds access";
if (code == 0x41) return "out of memory error";
if (code == 0x51) return "invalid internal function call";
return "unknown panic code";
}
/**
* @notice Convert bytes4 to hex string for error reporting
* @param _bytes The bytes4 to convert
* @return string The hex string representation (8 characters, no 0x prefix)
*/
function _toHexString(bytes4 _bytes) private pure returns (string memory) {
bytes memory hexChars = "0123456789abcdef";
bytes memory result = new bytes(8);
for (uint256 i = 0; i < 4; i++) {
result[i * 2] = hexChars[uint8(_bytes[i]) >> 4];
result[i * 2 + 1] = hexChars[uint8(_bytes[i]) & 0x0f];
}
return string(result);
}
}
contracts/module/base/SafeModuleBase.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
/**
* @title SafeModuleBase
* @author Manifest Finance
* @notice Shared auth, pause, two-step ownership and timelock primitives for Manifest Safe modules.
* PositionFeeModule and RewardDistributionModule inherit it. LiquidityModule and
* GuardedMintModule keep their own copies of these primitives on purpose: both are live
* and audited, so migrating them would add a fourth copy during the change rather than
* remove two. Their copies are no longer equivalent to this one: they raise a string
* require where this base reverts TimelockDelayExceedsExpiry, they enforce no uniqueness
* over (opType, payloadHash), and their queueSetAuthorizedBot accepts the bot that is
* already authorized. The allowlist half of the sequence UNIQUENESS describes below is
* therefore still reachable in both of them, through their own immediate removers; the bot
* half is not, because neither exposes an immediate clearAuthorizedBot. A new module should
* inherit this rather than copy them again.
* @dev TIMELOCK MODEL: the base stores only the operation's opType and a payload HASH, never the
* payload. The caller re-supplies the payload at execution and _consume rebinds it, so a queued
* operation cannot be executed with substituted arguments and cannot be replayed.
*
* UNIQUENESS: at most one live (unexecuted, uncancelled, unexpired) operation may exist for
* a given (opType, payloadHash). A second queue of the same action is rejected so a leftover
* operation cannot apply the same change later without a newly announced delay. Cancel or
* execute the live one before queueing it again. An expired leftover cannot execute, so it
* does not occupy the slot: the same payload may be announced again and starts a fresh delay.
* Different payloads of the same opType may be pending together.
*
* TIMELOCK SCOPE: the timelock gates the bot's identity and the set of things it may act on.
* It does not gate everything an owner can do, and that is deliberate. Clearing the bot is
* immediate, because a compromised key must be cuttable at once. setPaused is immediate in
* both directions, because a kill switch that takes hours to release is not usable. Ownership
* transfer is not timelocked because it is two-step: acceptOwnership requires the incoming
* owner to act, so a hijacked transferOwnership cannot complete on its own.
*/
abstract contract SafeModuleBase is ReentrancyGuard {
// ========================================
// CONSTANTS
// ========================================
/// @notice Default timelock delay applied when the constructor is passed 0
uint256 public constant DEFAULT_TIMELOCK_DELAY = 6 hours;
/// @notice How long after `executeAfter` a queued operation can still be executed. Execution is
/// allowed from `executeAfter` up to and including `executeAfter + TIMELOCK_EXPIRY`;
/// from the next second on, an attempt to execute reverts TimelockExpired
uint256 public constant TIMELOCK_EXPIRY = 7 days;
/// @notice opType reserved by the base. Children MUST use values >= 2.
uint8 public constant OP_SET_AUTHORIZED_BOT = 1;
/// @notice Timelock delay, fixed at construction. 0 selects DEFAULT_TIMELOCK_DELAY.
uint256 public immutable TIMELOCK_DELAY;
// ========================================
// STATE
// ========================================
/// @notice A queued timelock operation, as returned by getPendingOperation.
/// @param opType What kind of operation this is. 1 is the base's bot change; a child defines its
/// own values from 2 up
/// @param executed True once consumed. A consumed operation is never reusable
/// @param cancelled True once the owner cancelled it. Cancelling does not free the id for reuse
/// @param payloadHash keccak256 of the abi-encoded arguments the executor must re-supply
/// @param executeAfter Timestamp from which it may be executed. Zero means no such operation
/// exists, which is how getPendingOperation reports an unknown id
struct PendingOperation {
uint8 opType;
bool executed;
bool cancelled;
bytes32 payloadHash;
uint256 executeAfter;
}
/// @notice The single address allowed to call the child's bot-gated entry points. Zero after
/// clearAuthorizedBot, which leaves no address able to pass onlyAuthorizedBot
address public authorizedBot;
/// @notice The administrator: manages the bot, the pause and every timelocked operation
address public owner;
/// @notice Owner nominated by transferOwnership, pending its own acceptOwnership call
address public pendingOwner;
/// @notice While true, every function carrying notPaused reverts ModulePaused
bool public paused;
mapping(bytes32 => PendingOperation) private pendingOperations;
uint256 private _operationNonce;
/// @dev keccak256(opType, payloadHash) => the id of the last operation queued under that key.
/// A later queue of the same key overwrites it once that operation is executed, cancelled
/// or expired. Nothing ever clears the entry: _queueReserved decides whether the slot is
/// taken from the stored record's flags and its expiry, not from the entry's presence.
mapping(bytes32 => bytes32) private pendingByPayload;
// ========================================
// ERRORS
// ========================================
/// @notice The caller is not the authorized bot. Also raised when the bot has been cleared,
/// since no caller can then match the zero address
error OnlyAuthorizedBot();
/// @notice The caller is not the owner
error OnlyOwner();
/// @notice The caller is not the pending owner nominated by transferOwnership
error OnlyPendingOwner();
/// @notice The module is paused. Only functions carrying notPaused are affected; owner
/// administration, including unpausing, stays available
error ModulePaused();
/// @notice A zero address was supplied where one is not allowed: this constructor's bot or
/// owner, a new bot, or a new owner. Children raise the same error for their own
/// constructor arguments, since they do not redeclare it; PositionFeeModule does so for
/// its PositionManager and its Safe. Clearing the bot has its own function and is
/// unaffected
error InvalidAddress();
/// @notice queueSetAuthorizedBot was called with the address that is already authorized. A
/// no-op queue would mature while the bot is live and could re-authorize it after
/// clearAuthorizedBot with no newly announced delay.
error BotAlreadyAuthorized();
/// @notice cancelOwnershipTransfer was called with no transfer pending
error NoPendingOwnership();
/// @notice The timelock delay passed to the constructor is longer than TIMELOCK_EXPIRY
error TimelockDelayExceedsExpiry();
/// @notice No operation has ever been queued under this id. Records are never deleted, so an
/// executed or cancelled operation raises TimelockAlreadyExecuted or
/// TimelockAlreadyCancelled instead of this
/// @param operationId The id that resolved to no stored operation
error TimelockNotFound(bytes32 operationId);
/// @notice The operation exists but its delay has not elapsed yet
/// @param operationId The id that is not yet executable
error TimelockNotReady(bytes32 operationId);
/// @notice The operation's execution window has closed. It can never be executed and must be
/// queued again
/// @param operationId The id whose window has passed
error TimelockExpired(bytes32 operationId);
/// @notice The operation was already consumed. Execution is single-use
/// @param operationId The id that was already executed
error TimelockAlreadyExecuted(bytes32 operationId);
/// @notice The operation was cancelled by the owner and can never be executed
/// @param operationId The id that was cancelled
error TimelockAlreadyCancelled(bytes32 operationId);
/// @notice A live (unexecuted, uncancelled, unexpired) operation with the same type and payload
/// is already queued. Cancel it, or wait for it to execute, before announcing the same
/// change again. An expired leftover does not occupy the slot.
/// @param operationId The live operation occupying this (opType, payloadHash) slot
error TimelockAlreadyPending(bytes32 operationId);
/// @notice What the executor supplied does not rebind to what was queued. Raised for BOTH a
/// mismatched opType and a mismatched payload, so this error alone does not say which:
/// compare the arguments and the operation type against getPendingOperation
/// @param operationId The id whose stored type or payload hash did not match
error TimelockPayloadMismatch(bytes32 operationId);
/// @notice A child tried to queue or consume an opType outside the child range: either the
/// value the base reserves (OP_SET_AUTHORIZED_BOT) or zero. Children must use values
/// strictly greater than OP_SET_AUTHORIZED_BOT
error ReservedOpType();
// ========================================
// EVENTS
// ========================================
/// @notice The authorized bot was replaced through the timelock
/// @param previousBot The bot that was authorized until this call
/// @param newBot The bot authorized from now on
event AuthorizedBotChanged(address indexed previousBot, address indexed newBot);
/// @notice clearAuthorizedBot was called. No address can pass onlyAuthorizedBot until a new bot
/// is set. Like setPaused, the call has no equality guard, so a repeat emits again with
/// previousBot already zero and revokes nothing
/// @param previousBot The bot authorized until this call, or zero if there was none
event AuthorizedBotCleared(address indexed previousBot);
/// @notice The pause flag was written. Emitted on every setPaused call, including one that
/// writes the value it already held, so this event does not imply a change
/// @param paused The value now stored
event Paused(bool paused);
/// @notice An ownership transfer was nominated. Ownership has NOT moved yet: the nominee must
/// call acceptOwnership
/// @param currentOwner The owner at nomination time, still the owner after this event
/// @param pendingOwner The nominee
event OwnershipTransferStarted(address indexed currentOwner, address indexed pendingOwner);
/// @notice Ownership moved. This is the event that marks the actual handover
/// @param previousOwner The owner before the handover
/// @param newOwner The owner from now on
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/// @notice A pending ownership transfer was withdrawn before the nominee accepted it
/// @param owner The owner who withdrew it, unchanged by this call
/// @param cancelledPendingOwner The nominee whose nomination was withdrawn
event OwnershipTransferCancelled(address indexed owner, address indexed cancelledPendingOwner);
/// @notice An operation was queued. This is the announcement a third-party watcher reacts to:
/// it names the operation type and the moment it becomes executable, ahead of the change
/// @param operationId Handle needed to execute or cancel. Derived from an internal nonce and the
/// queueing context, so it cannot be recomputed from the payload alone
/// @param opType 1 for the base's bot change, or a child-defined value from 2 up
/// @param executeAfter Timestamp from which execution is allowed. The last timestamp inside
/// the window is executeAfter + TIMELOCK_EXPIRY
event TimelockQueued(bytes32 indexed operationId, uint8 indexed opType, uint256 executeAfter);
/// @notice A queued operation was consumed. Emitted while the timelock is being rebound, before
/// the operation's own effect, so an indexer sees this ahead of the effect's own event
/// @param operationId The id consumed
/// @param opType The type it was queued and consumed as
event TimelockExecuted(bytes32 indexed operationId, uint8 indexed opType);
/// @notice A queued operation was cancelled and can never be executed
/// @param operationId The id cancelled
event TimelockCancelled(bytes32 indexed operationId);
// ========================================
// MODIFIERS
// ========================================
modifier onlyAuthorizedBot() {
if (msg.sender != authorizedBot) revert OnlyAuthorizedBot();
_;
}
modifier onlyOwner() {
if (msg.sender != owner) revert OnlyOwner();
_;
}
modifier onlyPendingOwner() {
if (msg.sender != pendingOwner) revert OnlyPendingOwner();
_;
}
modifier notPaused() {
if (paused) revert ModulePaused();
_;
}
// ========================================
// CONSTRUCTOR
// ========================================
constructor(address _authorizedBot, address _owner, uint256 _timelockDelay) {
if (_authorizedBot == address(0)) revert InvalidAddress();
if (_owner == address(0)) revert InvalidAddress();
uint256 delay = _timelockDelay == 0 ? DEFAULT_TIMELOCK_DELAY : _timelockDelay;
// The delay is capped at TIMELOCK_EXPIRY, so a queued operation never waits longer than
// that before it can be executed.
if (delay > TIMELOCK_EXPIRY) revert TimelockDelayExceedsExpiry();
TIMELOCK_DELAY = delay;
authorizedBot = _authorizedBot;
owner = _owner;
}
// ========================================
// TIMELOCK PRIMITIVES (for children)
// ========================================
/// @dev Owner-gated queue used by the base's reserved opTypes and, through _queue, by every
/// child opType. The owner check is repeated here rather than relied on at the external
/// wrappers, so no future caller can reach the queue without it. Rejects a second live
/// (unexecuted, uncancelled, unexpired) operation of the same (opType, payloadHash) so a
/// leftover queue cannot re-apply a reversed change inside its original window. An expired
/// leftover does not occupy the slot.
function _queueReserved(uint8 opType, bytes32 payloadHash) private returns (bytes32 operationId) {
if (msg.sender != owner) revert OnlyOwner();
bytes32 key = keccak256(abi.encode(opType, payloadHash));
bytes32 existing = pendingByPayload[key];
if (existing != bytes32(0)) {
PendingOperation storage existingOp = pendingOperations[existing];
if (
!existingOp.executed && !existingOp.cancelled
&& block.timestamp <= existingOp.executeAfter + TIMELOCK_EXPIRY
) {
revert TimelockAlreadyPending(existing);
}
}
operationId = keccak256(abi.encodePacked(_operationNonce, address(this), msg.sender, block.timestamp));
unchecked {
++_operationNonce;
}
uint256 executeAfter = block.timestamp + TIMELOCK_DELAY;
pendingOperations[operationId] = PendingOperation({
opType: opType, executed: false, cancelled: false, payloadHash: payloadHash, executeAfter: executeAfter
});
pendingByPayload[key] = operationId;
emit TimelockQueued(operationId, opType, executeAfter);
}
/// @dev Owner-gated consume counterpart to _queueReserved. Reverts unless the operation exists,
/// is of the expected type, matches the supplied payload, is ready, unexpired, unexecuted
/// and uncancelled. Marks it executed before returning.
function _consumeReserved(bytes32 operationId, uint8 opType, bytes32 payloadHash) private {
if (msg.sender != owner) revert OnlyOwner();
PendingOperation storage op = pendingOperations[operationId];
if (op.executeAfter == 0) revert TimelockNotFound(operationId);
if (op.executed) revert TimelockAlreadyExecuted(operationId);
if (op.cancelled) revert TimelockAlreadyCancelled(operationId);
if (op.opType != opType) revert TimelockPayloadMismatch(operationId);
if (op.payloadHash != payloadHash) revert TimelockPayloadMismatch(operationId);
if (block.timestamp < op.executeAfter) revert TimelockNotReady(operationId);
if (block.timestamp > op.executeAfter + TIMELOCK_EXPIRY) revert TimelockExpired(operationId);
op.executed = true;
emit TimelockExecuted(operationId, opType);
}
/// @dev Owner-gating is enforced by _queueReserved itself, not left to caller discipline.
/// Children must use an opType strictly greater than OP_SET_AUTHORIZED_BOT; a reserved
/// opType is rejected here before it ever reaches storage. Hash the payload with
/// abi.encode rather than abi.encodePacked: UNIQUENESS treats one hash as one operation,
/// so a packed encoding that collapses two distinct payloads into one hash would have this
/// base reject a legitimate queue as a duplicate.
function _queue(uint8 opType, bytes32 payloadHash) internal returns (bytes32 operationId) {
if (opType <= OP_SET_AUTHORIZED_BOT) revert ReservedOpType();
operationId = _queueReserved(opType, payloadHash);
}
/// @dev Owner-gating is enforced by _consumeReserved itself, not left to caller discipline.
/// Children must use an opType strictly greater than OP_SET_AUTHORIZED_BOT; a reserved
/// opType is rejected here before it is ever consumed. See _consumeReserved for the full
/// revert contract.
function _consume(bytes32 operationId, uint8 opType, bytes32 payloadHash) internal {
if (opType <= OP_SET_AUTHORIZED_BOT) revert ReservedOpType();
_consumeReserved(operationId, opType, payloadHash);
}
// ========================================
// TIMELOCK ADMIN
// ========================================
/// @notice Cancels a queued operation permanently. The id is not freed for reuse.
/// @dev Reverts if the operation does not exist, was already executed, or was already cancelled.
/// @param operationId The queued operation to cancel
function cancelTimelock(bytes32 operationId) external onlyOwner {
PendingOperation storage op = pendingOperations[operationId];
if (op.executeAfter == 0) revert TimelockNotFound(operationId);
if (op.executed) revert TimelockAlreadyExecuted(operationId);
if (op.cancelled) revert TimelockAlreadyCancelled(operationId);
op.cancelled = true;
emit TimelockCancelled(operationId);
}
/// @notice Reads a queued operation. Never reverts.
/// @param operationId The operation to read
/// @return The stored record. An all-zero struct, recognisable by executeAfter == 0, means no
/// operation was ever queued under this id. Executed and cancelled operations are
/// retained with their flags set, not deleted
function getPendingOperation(bytes32 operationId) external view returns (PendingOperation memory) {
return pendingOperations[operationId];
}
// ========================================
// BOT MANAGEMENT
// ========================================
/// @notice Queues a bot replacement. The bot does not change until executeSetAuthorizedBot runs.
/// @dev To revoke rather than replace, use clearAuthorizedBot, which is immediate. A queue of
/// the already-authorized bot is rejected so a leftover cannot re-authorize it after a
/// clear without a newly announced delay.
/// @param newBot The bot to authorize once the timelock elapses. Must not be the zero address
/// or the currently authorized bot.
/// @return operationId Handle for executeSetAuthorizedBot or cancelTimelock. Retain it: it is
/// derived from an internal nonce and the queueing context, so it cannot be recomputed
/// from newBot
function queueSetAuthorizedBot(address newBot) external onlyOwner returns (bytes32 operationId) {
if (newBot == address(0)) revert InvalidAddress();
if (newBot == authorizedBot) revert BotAlreadyAuthorized();
operationId = _queueReserved(OP_SET_AUTHORIZED_BOT, keccak256(abi.encode(newBot)));
}
/// @notice Applies a queued bot replacement once its delay has elapsed.
/// @dev newBot must be identical to the one queued: it is rebound against the stored payload
/// hash. A mismatch reverts TimelockPayloadMismatch, as does an operationId that was
/// queued under a different operation type, such as a child's allowlist handle.
/// @param operationId The handle returned by queueSetAuthorizedBot
/// @param newBot The same address that was queued
function executeSetAuthorizedBot(bytes32 operationId, address newBot) external onlyOwner {
_consumeReserved(operationId, OP_SET_AUTHORIZED_BOT, keccak256(abi.encode(newBot)));
address previous = authorizedBot;
authorizedBot = newBot;
emit AuthorizedBotChanged(previous, newBot);
}
/// @notice Revokes the authorized bot immediately, leaving no bot until one is set again.
/// @dev Deliberately outside the timelock: a compromised bot key must be cuttable in the same
/// transaction, whatever TIMELOCK_DELAY is set to.
function clearAuthorizedBot() external onlyOwner {
address previous = authorizedBot;
authorizedBot = address(0);
emit AuthorizedBotCleared(previous);
}
// ========================================
// PAUSE
// ========================================
/// @notice The kill switch. Blocks every function carrying notPaused while true.
/// @dev Immediate in BOTH directions and deliberately outside the timelock: a switch that takes
/// hours to throw is not a kill switch, and one that takes hours to release is not usable.
/// Owner administration, including unpausing, keeps working while paused.
/// @param _paused True to block the gated entry points, false to release them
function setPaused(bool _paused) external onlyOwner {
paused = _paused;
emit Paused(_paused);
}
// ========================================
// OWNERSHIP (two-step)
// ========================================
/// @notice Nominates a new owner. This does NOT transfer ownership: the nominee must call
/// acceptOwnership, and the current owner keeps every power until they do.
/// @dev Two-step by design and therefore not timelocked: acceptOwnership must come from the
/// nominee, so a mistyped or uncontrolled address can never take ownership, and
/// cancelOwnershipTransfer withdraws a nomination before it is accepted. This does NOT
/// defend against a compromised owner key, which can nominate an address it controls and
/// accept from it in the same transaction. Nominating again overwrites the previous
/// nominee.
/// @param newOwner The address to nominate. Must not be the zero address
function transferOwnership(address newOwner) external onlyOwner {
if (newOwner == address(0)) revert InvalidAddress();
pendingOwner = newOwner;
emit OwnershipTransferStarted(owner, newOwner);
}
/// @notice Completes a nominated ownership transfer. Callable only by the nominee, and this is
/// the call that actually moves ownership.
function acceptOwnership() external onlyPendingOwner {
address previous = owner;
owner = pendingOwner;
pendingOwner = address(0);
emit OwnershipTransferred(previous, owner);
}
/// @notice Withdraws a pending nomination before the nominee accepts it.
/// @dev Reverts NoPendingOwnership when no transfer is pending.
function cancelOwnershipTransfer() external onlyOwner {
if (pendingOwner == address(0)) revert NoPendingOwnership();
address cancelled = pendingOwner;
pendingOwner = address(0);
emit OwnershipTransferCancelled(owner, cancelled);
}
}
contracts/module/interfaces/IPositionFeeModule.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;
/**
* @title IPositionFeeModule
* @author Manifest Finance
* @notice The collect entry point, the allowlist admin calls, and every error and event
* PositionFeeModule declares itself. Not the module's whole external surface: its auth,
* pause, ownership and timelock functions come from SafeModuleBase, and it also exposes
* getters for OP_ADD_TOKEN_ID and its three pinned immutables (POSITION_MANAGER, SAFE,
* EXPECTED_POOL_ID), none of which appear here.
*/
interface IPositionFeeModule {
// ========================================
// ERRORS
// ========================================
/// @notice tokenId is not on the collectable allowlist. Adding is timelocked; the constructor
/// seeds directly and removeTokenId is immediate.
error TokenIdNotCollectable(uint256 tokenId);
/// @notice tokenId is already on the allowlist
error TokenIdAlreadyCollectable(uint256 tokenId);
/// @notice The pinned Safe has not enabled this module
error ModuleNotEnabled();
/// @notice The pinned Safe is not ownerOf(tokenId)
error PositionNotOwnedBySafe(uint256 tokenId);
/// @notice tokenId does not resolve to EXPECTED_POOL_ID: it belongs to another pool, or, on the
/// constructor's seed path where no ownership check precedes it, was never minted
/// @param tokenId The position whose pool did not match
error UnexpectedPool(uint256 tokenId);
/// @notice A zero-liquidity position cannot be poked; v4-core would revert CannotUpdateEmptyPosition
error PositionEmpty(uint256 tokenId);
/// @notice The pinned pool has a native currency leg; balance accounting assumes ERC20 on both legs
error NativeCurrencyUnsupported();
/// @notice Constructor received an empty seed list; a seed position is how the constructor
/// obtains the PoolKey behind EXPECTED_POOL_ID
error NoInitialTokenIds();
/// @notice The pinned pool's hook has afterRemoveLiquidityReturnDelta enabled. The module's
/// fund-safety argument, that CLOSE_CURRENCY is always a credit to the Safe, holds only
/// for a hook that cannot turn a zero-liquidity decrease into a debit; such a hook could
/// make CLOSE_CURRENCY settle FROM the Safe via Permit2 instead.
error HookMayReturnRemoveDelta();
// InvalidAddress is deliberately not redeclared here: PositionFeeModule inherits it from both
// this interface and SafeModuleBase, and Solidity rejects the duplicate signature with Error
// (9097) "Identifier already declared" (reproduced on solc 0.8.26). The constructor's
// zero-address checks use the base's declaration.
// ========================================
// EVENTS
// ========================================
/// @notice Emitted after a successful collect. Zero amounts mean the position had accrued
/// nothing, which is a successful no-op rather than a failure.
/// @param tokenId The position collected from
/// @param amount0 The Safe's measured currency0 balance increase across the collect, in raw
/// units. A balance delta, not the position's gross accrued fees: anything else that
/// credited the Safe during the call, including the pool's synchronous remove callback,
/// is included here.
/// @param amount1 The same measurement for currency1
event FeesCollected(uint256 indexed tokenId, uint256 amount0, uint256 amount1);
/// @notice Emitted when a position becomes collectable, from constructor seeding or a
/// timelocked addition
/// @param tokenId The position added to the allowlist
event TokenIdAdded(uint256 indexed tokenId);
/// @notice Emitted when a position is removed from the allowlist. Removal is immediate.
/// @param tokenId The position removed
event TokenIdRemoved(uint256 indexed tokenId);
/// @notice Emitted once at construction, recording the module's permanent pinning
/// @param positionManager The PositionManager this module calls
/// @param safe The Safe that owns the positions and receives every collected fee
/// @param authorizedBot The bot authorized at deployment. Changeable later; this is the initial
/// value only
event PositionFeeModuleInitialized(
address indexed positionManager, address indexed safe, address indexed authorizedBot
);
// ========================================
// FUNCTIONS
// ========================================
function executeCollectFees(uint256 tokenId) external;
function queueAddTokenId(uint256 tokenId) external returns (bytes32 operationId);
function executeAddTokenId(bytes32 operationId, uint256 tokenId) external;
function removeTokenId(uint256 tokenId) external;
function getCollectableTokenIds() external view returns (uint256[] memory);
function isCollectable(uint256 tokenId) external view returns (bool);
function getVersion() external pure returns (string memory);
}
contracts/module/interfaces/ISafe.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;
interface ISafe {
enum Operation {
Call,
DelegateCall
}
/// @dev Allows a Module to execute a Safe transaction without any further confirmations.
/// @param to Destination address of module transaction.
/// @param value Ether value of module transaction.
/// @param data Data payload of module transaction.
/// @param operation Operation type of module transaction.
function execTransactionFromModule(address to, uint256 value, bytes calldata data, Operation operation)
external
returns (bool success);
/// @dev Allows a Module to execute a Safe transaction without any further confirmations and return data
/// @param to Destination address of module transaction.
/// @param value Ether value of module transaction.
/// @param data Data payload of module transaction.
/// @param operation Operation type of module transaction.
function execTransactionFromModuleReturnData(address to, uint256 value, bytes memory data, Operation operation)
external
returns (bool success, bytes memory returnData);
/// @dev Allows to execute a Safe transaction confirmed by required number of owners and then pays the account that submitted the transaction.
/// Note: The fees are always transferred, even if the user transaction fails.
/// @param to Destination address of Safe transaction.
/// @param value Ether value of Safe transaction.
/// @param data Data payload of Safe transaction.
/// @param operation Operation type of Safe transaction.
/// @param safeTxGas Gas that should be used for the Safe transaction.
/// @param baseGas Gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)
/// @param gasPrice Gas price that should be used for the payment calculation.
/// @param gasToken Token address (or 0 if ETH) that is used for the payment.
/// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
/// @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint8 v})
function execTransaction(
address to,
uint256 value,
bytes calldata data,
Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address payable refundReceiver,
bytes memory signatures
) external payable returns (bool success);
function enableModule(address module) external;
function isModuleEnabled(address module) external view returns (bool);
function approveHash(bytes32 hashToApprove) external;
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @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);
}
lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721.sol)
pragma solidity >=0.6.2;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC-721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC-721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
* {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the address zero.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol
// 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;
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @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);
}
lib/v4-core/src/interfaces/IExtsload.sol
// 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);
}
lib/v4-core/src/interfaces/IExttload.sol
// 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);
}
lib/v4-core/src/interfaces/IHooks.sol
// 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);
}
lib/v4-core/src/interfaces/IPoolManager.sol
// 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;
}
lib/v4-core/src/interfaces/IProtocolFees.sol
// 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);
}
lib/v4-core/src/interfaces/external/IERC20Minimal.sol
// 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);
}
lib/v4-core/src/interfaces/external/IERC6909Claims.sol
// 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);
}
lib/v4-core/src/libraries/CustomRevert.sol
// 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))
}
}
}
lib/v4-core/src/libraries/Hooks.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {SafeCast} from "./SafeCast.sol";
import {LPFeeLibrary} from "./LPFeeLibrary.sol";
import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "../types/BeforeSwapDelta.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {ParseBytes} from "./ParseBytes.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
library Hooks {
using LPFeeLibrary for uint24;
using Hooks for IHooks;
using SafeCast for int256;
using BeforeSwapDeltaLibrary for BeforeSwapDelta;
using ParseBytes for bytes;
using CustomRevert for bytes4;
uint160 internal constant ALL_HOOK_MASK = uint160((1 << 14) - 1);
uint160 internal constant BEFORE_INITIALIZE_FLAG = 1 << 13;
uint160 internal constant AFTER_INITIALIZE_FLAG = 1 << 12;
uint160 internal constant BEFORE_ADD_LIQUIDITY_FLAG = 1 << 11;
uint160 internal constant AFTER_ADD_LIQUIDITY_FLAG = 1 << 10;
uint160 internal constant BEFORE_REMOVE_LIQUIDITY_FLAG = 1 << 9;
uint160 internal constant AFTER_REMOVE_LIQUIDITY_FLAG = 1 << 8;
uint160 internal constant BEFORE_SWAP_FLAG = 1 << 7;
uint160 internal constant AFTER_SWAP_FLAG = 1 << 6;
uint160 internal constant BEFORE_DONATE_FLAG = 1 << 5;
uint160 internal constant AFTER_DONATE_FLAG = 1 << 4;
uint160 internal constant BEFORE_SWAP_RETURNS_DELTA_FLAG = 1 << 3;
uint160 internal constant AFTER_SWAP_RETURNS_DELTA_FLAG = 1 << 2;
uint160 internal constant AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 1;
uint160 internal constant AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 0;
struct Permissions {
bool beforeInitialize;
bool afterInitialize;
bool beforeAddLiquidity;
bool afterAddLiquidity;
bool beforeRemoveLiquidity;
bool afterRemoveLiquidity;
bool beforeSwap;
bool afterSwap;
bool beforeDonate;
bool afterDonate;
bool beforeSwapReturnDelta;
bool afterSwapReturnDelta;
bool afterAddLiquidityReturnDelta;
bool afterRemoveLiquidityReturnDelta;
}
/// @notice Thrown if the address will not lead to the specified hook calls being called
/// @param hooks The address of the hooks contract
error HookAddressNotValid(address hooks);
/// @notice Hook did not return its selector
error InvalidHookResponse();
/// @notice Additional context for ERC-7751 wrapped error when a hook call fails
error HookCallFailed();
/// @notice The hook's delta changed the swap from exactIn to exactOut or vice versa
error HookDeltaExceedsSwapAmount();
/// @notice Utility function intended to be used in hook constructors to ensure
/// the deployed hooks address causes the intended hooks to be called
/// @param permissions The hooks that are intended to be called
/// @dev permissions param is memory as the function will be called from constructors
function validateHookPermissions(IHooks self, Permissions memory permissions) internal pure {
if (
permissions.beforeInitialize != self.hasPermission(BEFORE_INITIALIZE_FLAG)
|| permissions.afterInitialize != self.hasPermission(AFTER_INITIALIZE_FLAG)
|| permissions.beforeAddLiquidity != self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)
|| permissions.afterAddLiquidity != self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)
|| permissions.beforeRemoveLiquidity != self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)
|| permissions.afterRemoveLiquidity != self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
|| permissions.beforeSwap != self.hasPermission(BEFORE_SWAP_FLAG)
|| permissions.afterSwap != self.hasPermission(AFTER_SWAP_FLAG)
|| permissions.beforeDonate != self.hasPermission(BEFORE_DONATE_FLAG)
|| permissions.afterDonate != self.hasPermission(AFTER_DONATE_FLAG)
|| permissions.beforeSwapReturnDelta != self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)
|| permissions.afterSwapReturnDelta != self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
|| permissions.afterAddLiquidityReturnDelta != self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
|| permissions.afterRemoveLiquidityReturnDelta
!= self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
) {
HookAddressNotValid.selector.revertWith(address(self));
}
}
/// @notice Ensures that the hook address includes at least one hook flag or dynamic fees, or is the 0 address
/// @param self The hook to verify
/// @param fee The fee of the pool the hook is used with
/// @return bool True if the hook address is valid
function isValidHookAddress(IHooks self, uint24 fee) internal pure returns (bool) {
// The hook can only have a flag to return a hook delta on an action if it also has the corresponding action flag
if (!self.hasPermission(BEFORE_SWAP_FLAG) && self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) return false;
if (!self.hasPermission(AFTER_SWAP_FLAG) && self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)) return false;
if (!self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) && self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG))
{
return false;
}
if (
!self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
&& self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
) return false;
// If there is no hook contract set, then fee cannot be dynamic
// If a hook contract is set, it must have at least 1 flag set, or have a dynamic fee
return address(self) == address(0)
? !fee.isDynamicFee()
: (uint160(address(self)) & ALL_HOOK_MASK > 0 || fee.isDynamicFee());
}
/// @notice performs a hook call using the given calldata on the given hook that doesn't return a delta
/// @return result The complete data returned by the hook
function callHook(IHooks self, bytes memory data) internal returns (bytes memory result) {
bool success;
assembly ("memory-safe") {
success := call(gas(), self, 0, add(data, 0x20), mload(data), 0, 0)
}
// Revert with FailedHookCall, containing any error message to bubble up
if (!success) CustomRevert.bubbleUpAndRevertWith(address(self), bytes4(data), HookCallFailed.selector);
// The call was successful, fetch the returned data
assembly ("memory-safe") {
// allocate result byte array from the free memory pointer
result := mload(0x40)
// store new free memory pointer at the end of the array padded to 32 bytes
mstore(0x40, add(result, and(add(returndatasize(), 0x3f), not(0x1f))))
// store length in memory
mstore(result, returndatasize())
// copy return data to result
returndatacopy(add(result, 0x20), 0, returndatasize())
}
// Length must be at least 32 to contain the selector. Check expected selector and returned selector match.
if (result.length < 32 || result.parseSelector() != data.parseSelector()) {
InvalidHookResponse.selector.revertWith();
}
}
/// @notice performs a hook call using the given calldata on the given hook
/// @return int256 The delta returned by the hook
function callHookWithReturnDelta(IHooks self, bytes memory data, bool parseReturn) internal returns (int256) {
bytes memory result = callHook(self, data);
// If this hook wasn't meant to return something, default to 0 delta
if (!parseReturn) return 0;
// A length of 64 bytes is required to return a bytes4, and a 32 byte delta
if (result.length != 64) InvalidHookResponse.selector.revertWith();
return result.parseReturnDelta();
}
/// @notice modifier to prevent calling a hook if they initiated the action
modifier noSelfCall(IHooks self) {
if (msg.sender != address(self)) {
_;
}
}
/// @notice calls beforeInitialize hook if permissioned and validates return value
function beforeInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96) internal noSelfCall(self) {
if (self.hasPermission(BEFORE_INITIALIZE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeInitialize, (msg.sender, key, sqrtPriceX96)));
}
}
/// @notice calls afterInitialize hook if permissioned and validates return value
function afterInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96, int24 tick)
internal
noSelfCall(self)
{
if (self.hasPermission(AFTER_INITIALIZE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.afterInitialize, (msg.sender, key, sqrtPriceX96, tick)));
}
}
/// @notice calls beforeModifyLiquidity hook if permissioned and validates return value
function beforeModifyLiquidity(
IHooks self,
PoolKey memory key,
ModifyLiquidityParams memory params,
bytes calldata hookData
) internal noSelfCall(self) {
if (params.liquidityDelta > 0 && self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeAddLiquidity, (msg.sender, key, params, hookData)));
} else if (params.liquidityDelta <= 0 && self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeRemoveLiquidity, (msg.sender, key, params, hookData)));
}
}
/// @notice calls afterModifyLiquidity hook if permissioned and validates return value
function afterModifyLiquidity(
IHooks self,
PoolKey memory key,
ModifyLiquidityParams memory params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) internal returns (BalanceDelta callerDelta, BalanceDelta hookDelta) {
if (msg.sender == address(self)) return (delta, BalanceDeltaLibrary.ZERO_DELTA);
callerDelta = delta;
if (params.liquidityDelta > 0) {
if (self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)) {
hookDelta = BalanceDelta.wrap(
self.callHookWithReturnDelta(
abi.encodeCall(
IHooks.afterAddLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
),
self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
)
);
callerDelta = callerDelta - hookDelta;
}
} else {
if (self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)) {
hookDelta = BalanceDelta.wrap(
self.callHookWithReturnDelta(
abi.encodeCall(
IHooks.afterRemoveLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
),
self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
)
);
callerDelta = callerDelta - hookDelta;
}
}
}
/// @notice calls beforeSwap hook if permissioned and validates return value
function beforeSwap(IHooks self, PoolKey memory key, SwapParams memory params, bytes calldata hookData)
internal
returns (int256 amountToSwap, BeforeSwapDelta hookReturn, uint24 lpFeeOverride)
{
amountToSwap = params.amountSpecified;
if (msg.sender == address(self)) return (amountToSwap, BeforeSwapDeltaLibrary.ZERO_DELTA, lpFeeOverride);
if (self.hasPermission(BEFORE_SWAP_FLAG)) {
bytes memory result = callHook(self, abi.encodeCall(IHooks.beforeSwap, (msg.sender, key, params, hookData)));
// A length of 96 bytes is required to return a bytes4, a 32 byte delta, and an LP fee
if (result.length != 96) InvalidHookResponse.selector.revertWith();
// dynamic fee pools that want to override the cache fee, return a valid fee with the override flag. If override flag
// is set but an invalid fee is returned, the transaction will revert. Otherwise the current LP fee will be used
if (key.fee.isDynamicFee()) lpFeeOverride = result.parseFee();
// skip this logic for the case where the hook return is 0
if (self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) {
hookReturn = BeforeSwapDelta.wrap(result.parseReturnDelta());
// any return in unspecified is passed to the afterSwap hook for handling
int128 hookDeltaSpecified = hookReturn.getSpecifiedDelta();
// Update the swap amount according to the hook's return, and check that the swap type doesn't change (exact input/output)
if (hookDeltaSpecified != 0) {
bool exactInput = amountToSwap < 0;
amountToSwap += hookDeltaSpecified;
if (exactInput ? amountToSwap > 0 : amountToSwap < 0) {
HookDeltaExceedsSwapAmount.selector.revertWith();
}
}
}
}
}
/// @notice calls afterSwap hook if permissioned and validates return value
function afterSwap(
IHooks self,
PoolKey memory key,
SwapParams memory params,
BalanceDelta swapDelta,
bytes calldata hookData,
BeforeSwapDelta beforeSwapHookReturn
) internal returns (BalanceDelta, BalanceDelta) {
if (msg.sender == address(self)) return (swapDelta, BalanceDeltaLibrary.ZERO_DELTA);
int128 hookDeltaSpecified = beforeSwapHookReturn.getSpecifiedDelta();
int128 hookDeltaUnspecified = beforeSwapHookReturn.getUnspecifiedDelta();
if (self.hasPermission(AFTER_SWAP_FLAG)) {
hookDeltaUnspecified += self.callHookWithReturnDelta(
abi.encodeCall(IHooks.afterSwap, (msg.sender, key, params, swapDelta, hookData)),
self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
).toInt128();
}
BalanceDelta hookDelta;
if (hookDeltaUnspecified != 0 || hookDeltaSpecified != 0) {
hookDelta = (params.amountSpecified < 0 == params.zeroForOne)
? toBalanceDelta(hookDeltaSpecified, hookDeltaUnspecified)
: toBalanceDelta(hookDeltaUnspecified, hookDeltaSpecified);
// the caller has to pay for (or receive) the hook's delta
swapDelta = swapDelta - hookDelta;
}
return (swapDelta, hookDelta);
}
/// @notice calls beforeDonate hook if permissioned and validates return value
function beforeDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
internal
noSelfCall(self)
{
if (self.hasPermission(BEFORE_DONATE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeDonate, (msg.sender, key, amount0, amount1, hookData)));
}
}
/// @notice calls afterDonate hook if permissioned and validates return value
function afterDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
internal
noSelfCall(self)
{
if (self.hasPermission(AFTER_DONATE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.afterDonate, (msg.sender, key, amount0, amount1, hookData)));
}
}
function hasPermission(IHooks self, uint160 flag) internal pure returns (bool) {
return uint160(address(self)) & flag != 0;
}
}
lib/v4-core/src/libraries/LPFeeLibrary.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @notice Library of helper functions for a pools LP fee
library LPFeeLibrary {
using LPFeeLibrary for uint24;
using CustomRevert for bytes4;
/// @notice Thrown when the static or dynamic fee on a pool exceeds 100%.
error LPFeeTooLarge(uint24 fee);
/// @notice An lp fee of exactly 0b1000000... signals a dynamic fee pool. This isn't a valid static fee as it is > MAX_LP_FEE
uint24 public constant DYNAMIC_FEE_FLAG = 0x800000;
/// @notice the second bit of the fee returned by beforeSwap is used to signal if the stored LP fee should be overridden in this swap
// only dynamic-fee pools can return a fee via the beforeSwap hook
uint24 public constant OVERRIDE_FEE_FLAG = 0x400000;
/// @notice mask to remove the override fee flag from a fee returned by the beforeSwaphook
uint24 public constant REMOVE_OVERRIDE_MASK = 0xBFFFFF;
/// @notice the lp fee is represented in hundredths of a bip, so the max is 100%
uint24 public constant MAX_LP_FEE = 1000000;
/// @notice returns true if a pool's LP fee signals that the pool has a dynamic fee
/// @param self The fee to check
/// @return bool True of the fee is dynamic
function isDynamicFee(uint24 self) internal pure returns (bool) {
return self == DYNAMIC_FEE_FLAG;
}
/// @notice returns true if an LP fee is valid, aka not above the maximum permitted fee
/// @param self The fee to check
/// @return bool True of the fee is valid
function isValid(uint24 self) internal pure returns (bool) {
return self <= MAX_LP_FEE;
}
/// @notice validates whether an LP fee is larger than the maximum, and reverts if invalid
/// @param self The fee to validate
function validate(uint24 self) internal pure {
if (!self.isValid()) LPFeeTooLarge.selector.revertWith(self);
}
/// @notice gets and validates the initial LP fee for a pool. Dynamic fee pools have an initial fee of 0.
/// @dev if a dynamic fee pool wants a non-0 initial fee, it should call `updateDynamicLPFee` in the afterInitialize hook
/// @param self The fee to get the initial LP from
/// @return initialFee 0 if the fee is dynamic, otherwise the fee (if valid)
function getInitialLPFee(uint24 self) internal pure returns (uint24) {
// the initial fee for a dynamic fee pool is 0
if (self.isDynamicFee()) return 0;
self.validate();
return self;
}
/// @notice returns true if the fee has the override flag set (2nd highest bit of the uint24)
/// @param self The fee to check
/// @return bool True of the fee has the override flag set
function isOverride(uint24 self) internal pure returns (bool) {
return self & OVERRIDE_FEE_FLAG != 0;
}
/// @notice returns a fee with the override flag removed
/// @param self The fee to remove the override flag from
/// @return fee The fee without the override flag set
function removeOverrideFlag(uint24 self) internal pure returns (uint24) {
return self & REMOVE_OVERRIDE_MASK;
}
/// @notice Removes the override flag and validates the fee (reverts if the fee is too large)
/// @param self The fee to remove the override flag from, and then validate
/// @return fee The fee without the override flag set (if valid)
function removeOverrideFlagAndValidate(uint24 self) internal pure returns (uint24 fee) {
fee = self.removeOverrideFlag();
fee.validate();
}
}
lib/v4-core/src/libraries/ParseBytes.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Parses bytes returned from hooks and the byte selector used to check return selectors from hooks.
/// @dev parseSelector also is used to parse the expected selector
/// For parsing hook returns, note that all hooks return either bytes4 or (bytes4, 32-byte-delta) or (bytes4, 32-byte-delta, uint24).
library ParseBytes {
function parseSelector(bytes memory result) internal pure returns (bytes4 selector) {
// equivalent: (selector,) = abi.decode(result, (bytes4, int256));
assembly ("memory-safe") {
selector := mload(add(result, 0x20))
}
}
function parseFee(bytes memory result) internal pure returns (uint24 lpFee) {
// equivalent: (,, lpFee) = abi.decode(result, (bytes4, int256, uint24));
assembly ("memory-safe") {
lpFee := mload(add(result, 0x60))
}
}
function parseReturnDelta(bytes memory result) internal pure returns (int256 hookReturn) {
// equivalent: (, hookReturnDelta) = abi.decode(result, (bytes4, int256));
assembly ("memory-safe") {
hookReturn := mload(add(result, 0x40))
}
}
}
lib/v4-core/src/libraries/SafeCast.sol
// 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));
}
}
lib/v4-core/src/types/BalanceDelta.sol
// 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)
}
}
}
lib/v4-core/src/types/BeforeSwapDelta.sol
// 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)
}
}
}
lib/v4-core/src/types/Currency.sol
// 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)));
}
}
lib/v4-core/src/types/PoolId.sol
// 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)
}
}
}
lib/v4-core/src/types/PoolKey.sol
// 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;
}
lib/v4-core/src/types/PoolOperation.sol
// 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;
}
lib/v4-periphery/lib/permit2/src/interfaces/IAllowanceTransfer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IEIP712} from "./IEIP712.sol";
/// @title AllowanceTransfer
/// @notice Handles ERC20 token permissions through signature based allowance setting and ERC20 token transfers by checking allowed amounts
/// @dev Requires user's token approval on the Permit2 contract
interface IAllowanceTransfer is IEIP712 {
/// @notice Thrown when an allowance on a token has expired.
/// @param deadline The timestamp at which the allowed amount is no longer valid
error AllowanceExpired(uint256 deadline);
/// @notice Thrown when an allowance on a token has been depleted.
/// @param amount The maximum amount allowed
error InsufficientAllowance(uint256 amount);
/// @notice Thrown when too many nonces are invalidated.
error ExcessiveInvalidation();
/// @notice Emits an event when the owner successfully invalidates an ordered nonce.
event NonceInvalidation(
address indexed owner, address indexed token, address indexed spender, uint48 newNonce, uint48 oldNonce
);
/// @notice Emits an event when the owner successfully sets permissions on a token for the spender.
event Approval(
address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration
);
/// @notice Emits an event when the owner successfully sets permissions using a permit signature on a token for the spender.
event Permit(
address indexed owner,
address indexed token,
address indexed spender,
uint160 amount,
uint48 expiration,
uint48 nonce
);
/// @notice Emits an event when the owner sets the allowance back to 0 with the lockdown function.
event Lockdown(address indexed owner, address token, address spender);
/// @notice The permit data for a token
struct PermitDetails {
// ERC20 token address
address token;
// the maximum amount allowed to spend
uint160 amount;
// timestamp at which a spender's token allowances become invalid
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
/// @notice The permit message signed for a single token allowance
struct PermitSingle {
// the permit data for a single token alownce
PermitDetails details;
// address permissioned on the allowed tokens
address spender;
// deadline on the permit signature
uint256 sigDeadline;
}
/// @notice The permit message signed for multiple token allowances
struct PermitBatch {
// the permit data for multiple token allowances
PermitDetails[] details;
// address permissioned on the allowed tokens
address spender;
// deadline on the permit signature
uint256 sigDeadline;
}
/// @notice The saved permissions
/// @dev This info is saved per owner, per token, per spender and all signed over in the permit message
/// @dev Setting amount to type(uint160).max sets an unlimited approval
struct PackedAllowance {
// amount allowed
uint160 amount;
// permission expiry
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
/// @notice A token spender pair.
struct TokenSpenderPair {
// the token the spender is approved
address token;
// the spender address
address spender;
}
/// @notice Details for a token transfer.
struct AllowanceTransferDetails {
// the owner of the token
address from;
// the recipient of the token
address to;
// the amount of the token
uint160 amount;
// the token to be transferred
address token;
}
/// @notice A mapping from owner address to token address to spender address to PackedAllowance struct, which contains details and conditions of the approval.
/// @notice The mapping is indexed in the above order see: allowance[ownerAddress][tokenAddress][spenderAddress]
/// @dev The packed slot holds the allowed amount, expiration at which the allowed amount is no longer valid, and current nonce thats updated on any signature based approvals.
function allowance(address user, address token, address spender)
external
view
returns (uint160 amount, uint48 expiration, uint48 nonce);
/// @notice Approves the spender to use up to amount of the specified token up until the expiration
/// @param token The token to approve
/// @param spender The spender address to approve
/// @param amount The approved amount of the token
/// @param expiration The timestamp at which the approval is no longer valid
/// @dev The packed allowance also holds a nonce, which will stay unchanged in approve
/// @dev Setting amount to type(uint160).max sets an unlimited approval
function approve(address token, address spender, uint160 amount, uint48 expiration) external;
/// @notice Permit a spender to a given amount of the owners token via the owner's EIP-712 signature
/// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
/// @param owner The owner of the tokens being approved
/// @param permitSingle Data signed over by the owner specifying the terms of approval
/// @param signature The owner's signature over the permit data
function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external;
/// @notice Permit a spender to the signed amounts of the owners tokens via the owner's EIP-712 signature
/// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
/// @param owner The owner of the tokens being approved
/// @param permitBatch Data signed over by the owner specifying the terms of approval
/// @param signature The owner's signature over the permit data
function permit(address owner, PermitBatch memory permitBatch, bytes calldata signature) external;
/// @notice Transfer approved tokens from one address to another
/// @param from The address to transfer from
/// @param to The address of the recipient
/// @param amount The amount of the token to transfer
/// @param token The token address to transfer
/// @dev Requires the from address to have approved at least the desired amount
/// of tokens to msg.sender.
function transferFrom(address from, address to, uint160 amount, address token) external;
/// @notice Transfer approved tokens in a batch
/// @param transferDetails Array of owners, recipients, amounts, and tokens for the transfers
/// @dev Requires the from addresses to have approved at least the desired amount
/// of tokens to msg.sender.
function transferFrom(AllowanceTransferDetails[] calldata transferDetails) external;
/// @notice Enables performing a "lockdown" of the sender's Permit2 identity
/// by batch revoking approvals
/// @param approvals Array of approvals to revoke.
function lockdown(TokenSpenderPair[] calldata approvals) external;
/// @notice Invalidate nonces for a given (token, spender) pair
/// @param token The token to invalidate nonces for
/// @param spender The spender to invalidate nonces for
/// @param newNonce The new nonce to set. Invalidates all nonces less than it.
/// @dev Can't invalidate more than 2**16 nonces per transaction.
function invalidateNonces(address token, address spender, uint48 newNonce) external;
}
lib/v4-periphery/lib/permit2/src/interfaces/IEIP712.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IEIP712 {
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
lib/v4-periphery/src/interfaces/IEIP712_v4.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IEIP712_v4
/// @notice Interface for the EIP712 contract
interface IEIP712_v4 {
/// @notice Returns the domain separator for the current chain.
/// @return bytes32 The domain separator
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
lib/v4-periphery/src/interfaces/IERC721Permit_v4.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IERC721Permit_v4
/// @notice Interface for the ERC721Permit_v4 contract
interface IERC721Permit_v4 {
error SignatureDeadlineExpired();
error NoSelfPermit();
error Unauthorized();
/// @notice Approve of a specific token ID for spending by spender via signature
/// @param spender The account that is being approved
/// @param tokenId The ID of the token that is being approved for spending
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param nonce a unique value, for an owner, to prevent replay attacks; an unordered nonce where the top 248 bits correspond to a word and the bottom 8 bits calculate the bit position of the word
/// @param signature Concatenated data from a valid secp256k1 signature from the holder, i.e. abi.encodePacked(r, s, v)
/// @dev payable so it can be multicalled with NATIVE related actions
function permit(address spender, uint256 tokenId, uint256 deadline, uint256 nonce, bytes calldata signature)
external
payable;
/// @notice Set an operator with full permission to an owner's tokens via signature
/// @param owner The address that is setting the operator
/// @param operator The address that will be set as an operator for the owner
/// @param approved The permission to set on the operator
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param nonce a unique value, for an owner, to prevent replay attacks; an unordered nonce where the top 248 bits correspond to a word and the bottom 8 bits calculate the bit position of the word
/// @param signature Concatenated data from a valid secp256k1 signature from the holder, i.e. abi.encodePacked(r, s, v)
/// @dev payable so it can be multicalled with NATIVE related actions
function permitForAll(
address owner,
address operator,
bool approved,
uint256 deadline,
uint256 nonce,
bytes calldata signature
) external payable;
}
lib/v4-periphery/src/interfaces/IImmutableState.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
/// @title IImmutableState
/// @notice Interface for the ImmutableState contract
interface IImmutableState {
/// @notice The Uniswap v4 PoolManager contract
function poolManager() external view returns (IPoolManager);
}
lib/v4-periphery/src/interfaces/IMulticall_v4.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IMulticall_v4
/// @notice Interface for the Multicall_v4 contract
interface IMulticall_v4 {
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
/// @dev The `msg.value` is passed onto all subcalls, even if a previous subcall has consumed the ether.
/// Subcalls can instead use `address(this).value` to see the available ETH, and consume it using {value: x}.
/// @param data The encoded function data for each of the calls to make to this contract
/// @return results The results from each of the calls passed in via data
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}
lib/v4-periphery/src/interfaces/INotifier.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {ISubscriber} from "./ISubscriber.sol";
/// @title INotifier
/// @notice Interface for the Notifier contract
interface INotifier {
/// @notice Thrown when unsubscribing without a subscriber
error NotSubscribed();
/// @notice Thrown when a subscriber does not have code
error NoCodeSubscriber();
/// @notice Thrown when a user specifies a gas limit too low to avoid valid unsubscribe notifications
error GasLimitTooLow();
/// @notice Wraps the revert message of the subscriber contract on a reverting subscription
error SubscriptionReverted(address subscriber, bytes reason);
/// @notice Wraps the revert message of the subscriber contract on a reverting modify liquidity notification
error ModifyLiquidityNotificationReverted(address subscriber, bytes reason);
/// @notice Wraps the revert message of the subscriber contract on a reverting burn notification
error BurnNotificationReverted(address subscriber, bytes reason);
/// @notice Thrown when a tokenId already has a subscriber
error AlreadySubscribed(uint256 tokenId, address subscriber);
/// @notice Emitted on a successful call to subscribe
event Subscription(uint256 indexed tokenId, address indexed subscriber);
/// @notice Emitted on a successful call to unsubscribe
event Unsubscription(uint256 indexed tokenId, address indexed subscriber);
/// @notice Returns the subscriber for a respective position
/// @param tokenId the ERC721 tokenId
/// @return subscriber the subscriber contract
function subscriber(uint256 tokenId) external view returns (ISubscriber subscriber);
/// @notice Enables the subscriber to receive notifications for a respective position
/// @param tokenId the ERC721 tokenId
/// @param newSubscriber the address of the subscriber contract
/// @param data caller-provided data that's forwarded to the subscriber contract
/// @dev Calling subscribe when a position is already subscribed will revert
/// @dev payable so it can be multicalled with NATIVE related actions
/// @dev will revert if pool manager is locked
function subscribe(uint256 tokenId, address newSubscriber, bytes calldata data) external payable;
/// @notice Removes the subscriber from receiving notifications for a respective position
/// @param tokenId the ERC721 tokenId
/// @dev Callers must specify a high gas limit (remaining gas should be higher than unsubscriberGasLimit) such that the subscriber can be notified
/// @dev payable so it can be multicalled with NATIVE related actions
/// @dev Must always allow a user to unsubscribe. In the case of a malicious subscriber, a user can always unsubscribe safely, ensuring liquidity is always modifiable.
/// @dev will revert if pool manager is locked
function unsubscribe(uint256 tokenId) external payable;
/// @notice Returns and determines the maximum allowable gas-used for notifying unsubscribe
/// @return uint256 the maximum gas limit when notifying a subscriber's `notifyUnsubscribe` function
function unsubscribeGasLimit() external view returns (uint256);
}
lib/v4-periphery/src/interfaces/IPermit2Forwarder.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IAllowanceTransfer} from "permit2/src/interfaces/IAllowanceTransfer.sol";
/// @title IPermit2Forwarder
/// @notice Interface for the Permit2Forwarder contract
interface IPermit2Forwarder {
/// @notice allows forwarding a single permit to permit2
/// @dev this function is payable to allow multicall with NATIVE based actions
/// @param owner the owner of the tokens
/// @param permitSingle the permit data
/// @param signature the signature of the permit; abi.encodePacked(r, s, v)
/// @return err the error returned by a reverting permit call, empty if successful
function permit(address owner, IAllowanceTransfer.PermitSingle calldata permitSingle, bytes calldata signature)
external
payable
returns (bytes memory err);
/// @notice allows forwarding batch permits to permit2
/// @dev this function is payable to allow multicall with NATIVE based actions
/// @param owner the owner of the tokens
/// @param _permitBatch a batch of approvals
/// @param signature the signature of the permit; abi.encodePacked(r, s, v)
/// @return err the error returned by a reverting permit call, empty if successful
function permitBatch(address owner, IAllowanceTransfer.PermitBatch calldata _permitBatch, bytes calldata signature)
external
payable
returns (bytes memory err);
}
lib/v4-periphery/src/interfaces/IPoolInitializer_v4.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
/// @title IPoolInitializer_v4
/// @notice Interface for the PoolInitializer_v4 contract
interface IPoolInitializer_v4 {
/// @notice Initialize a Uniswap v4 Pool
/// @dev If the pool is already initialized, this function will not revert and just return type(int24).max
/// @param key The PoolKey of the pool to initialize
/// @param sqrtPriceX96 The initial starting price of the pool, expressed as a sqrtPriceX96
/// @return The current tick of the pool, or type(int24).max if the pool creation failed, or the pool already existed
function initializePool(PoolKey calldata key, uint160 sqrtPriceX96) external payable returns (int24);
}
lib/v4-periphery/src/interfaces/IPositionManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PositionInfo} from "../libraries/PositionInfoLibrary.sol";
import {INotifier} from "./INotifier.sol";
import {IImmutableState} from "./IImmutableState.sol";
import {IERC721Permit_v4} from "./IERC721Permit_v4.sol";
import {IEIP712_v4} from "./IEIP712_v4.sol";
import {IMulticall_v4} from "./IMulticall_v4.sol";
import {IPoolInitializer_v4} from "./IPoolInitializer_v4.sol";
import {IUnorderedNonce} from "./IUnorderedNonce.sol";
import {IPermit2Forwarder} from "./IPermit2Forwarder.sol";
/// @title IPositionManager
/// @notice Interface for the PositionManager contract
interface IPositionManager is
INotifier,
IImmutableState,
IERC721Permit_v4,
IEIP712_v4,
IMulticall_v4,
IPoolInitializer_v4,
IUnorderedNonce,
IPermit2Forwarder
{
/// @notice Thrown when the caller is not approved to modify a position
error NotApproved(address caller);
/// @notice Thrown when the block.timestamp exceeds the user-provided deadline
error DeadlinePassed(uint256 deadline);
/// @notice Thrown when calling transfer, subscribe, or unsubscribe when the PoolManager is unlocked.
/// @dev This is to prevent hooks from being able to trigger notifications at the same time the position is being modified.
error PoolManagerMustBeLocked();
/// @notice Unlocks Uniswap v4 PoolManager and batches actions for modifying liquidity
/// @dev This is the standard entrypoint for the PositionManager
/// @param unlockData is an encoding of actions, and parameters for those actions
/// @param deadline is the deadline for the batched actions to be executed
function modifyLiquidities(bytes calldata unlockData, uint256 deadline) external payable;
/// @notice Batches actions for modifying liquidity without unlocking v4 PoolManager
/// @dev This must be called by a contract that has already unlocked the v4 PoolManager
/// @param actions the actions to perform
/// @param params the parameters to provide for the actions
function modifyLiquiditiesWithoutUnlock(bytes calldata actions, bytes[] calldata params) external payable;
/// @notice Used to get the ID that will be used for the next minted liquidity position
/// @return uint256 The next token ID
function nextTokenId() external view returns (uint256);
/// @notice Returns the liquidity of a position
/// @param tokenId the ERC721 tokenId
/// @return liquidity the position's liquidity, as a liquidityAmount
/// @dev this value can be processed as an amount0 and amount1 by using the LiquidityAmounts library
function getPositionLiquidity(uint256 tokenId) external view returns (uint128 liquidity);
/// @notice Returns the pool key and position info of a position
/// @param tokenId the ERC721 tokenId
/// @return poolKey the pool key of the position
/// @return PositionInfo a uint256 packed value holding information about the position including the range (tickLower, tickUpper)
function getPoolAndPositionInfo(uint256 tokenId) external view returns (PoolKey memory, PositionInfo);
/// @notice Returns the position info of a position
/// @param tokenId the ERC721 tokenId
/// @return a uint256 packed value holding information about the position including the range (tickLower, tickUpper)
function positionInfo(uint256 tokenId) external view returns (PositionInfo);
}
lib/v4-periphery/src/interfaces/ISubscriber.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {PositionInfo} from "../libraries/PositionInfoLibrary.sol";
/// @title ISubscriber
/// @notice Interface that a Subscriber contract should implement to receive updates from the v4 position manager
interface ISubscriber {
/// @notice Called when a position subscribes to this subscriber contract
/// @param tokenId the token ID of the position
/// @param data additional data passed in by the caller
function notifySubscribe(uint256 tokenId, bytes memory data) external;
/// @notice Called when a position unsubscribes from the subscriber
/// @dev This call's gas is capped at `unsubscribeGasLimit` (set at deployment)
/// @dev Because of EIP-150, solidity may only allocate 63/64 of gasleft()
/// @param tokenId the token ID of the position
function notifyUnsubscribe(uint256 tokenId) external;
/// @notice Called when a position is burned
/// @param tokenId the token ID of the position
/// @param owner the current owner of the tokenId
/// @param info information about the position
/// @param liquidity the amount of liquidity decreased in the position, may be 0
/// @param feesAccrued the fees accrued by the position if liquidity was decreased
function notifyBurn(uint256 tokenId, address owner, PositionInfo info, uint256 liquidity, BalanceDelta feesAccrued)
external;
/// @notice Called when a position modifies its liquidity or collects fees
/// @param tokenId the token ID of the position
/// @param liquidityChange the change in liquidity on the underlying position
/// @param feesAccrued the fees to be collected from the position as a result of the modifyLiquidity call
/// @dev Note that feesAccrued can be artificially inflated by a malicious user
/// Pools with a single liquidity position can inflate feeGrowthGlobal (and consequently feesAccrued) by donating to themselves;
/// atomically donating and collecting fees within the same unlockCallback may further inflate feeGrowthGlobal/feesAccrued
function notifyModifyLiquidity(uint256 tokenId, int256 liquidityChange, BalanceDelta feesAccrued) external;
}
lib/v4-periphery/src/interfaces/IUnorderedNonce.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IUnorderedNonce
/// @notice Interface for the UnorderedNonce contract
interface IUnorderedNonce {
error NonceAlreadyUsed();
/// @notice mapping of nonces consumed by each address, where a nonce is a single bit on the 256-bit bitmap
/// @dev word is at most type(uint248).max
function nonces(address owner, uint256 word) external view returns (uint256);
/// @notice Revoke a nonce by spending it, preventing it from being used again
/// @dev Used in cases where a valid nonce has not been broadcasted onchain, and the owner wants to revoke the validity of the nonce
/// @dev payable so it can be multicalled with native-token related actions
function revokeNonce(uint256 nonce) external payable;
}
lib/v4-periphery/src/libraries/PositionInfoLibrary.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
/**
* @dev PositionInfo is a packed version of solidity structure.
* Using the packaged version saves gas and memory by not storing the structure fields in memory slots.
*
* Layout:
* 200 bits poolId | 24 bits tickUpper | 24 bits tickLower | 8 bits hasSubscriber
*
* Fields in the direction from the least significant bit:
*
* A flag to know if the tokenId is subscribed to an address
* uint8 hasSubscriber;
*
* The tickUpper of the position
* int24 tickUpper;
*
* The tickLower of the position
* int24 tickLower;
*
* The truncated poolId. Truncates a bytes32 value so the most signifcant (highest) 200 bits are used.
* bytes25 poolId;
*
* Note: If more bits are needed, hasSubscriber can be a single bit.
*
*/
type PositionInfo is uint256;
using PositionInfoLibrary for PositionInfo global;
library PositionInfoLibrary {
PositionInfo internal constant EMPTY_POSITION_INFO = PositionInfo.wrap(0);
uint256 internal constant MASK_UPPER_200_BITS = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000;
uint256 internal constant MASK_8_BITS = 0xFF;
uint24 internal constant MASK_24_BITS = 0xFFFFFF;
uint256 internal constant SET_UNSUBSCRIBE = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00;
uint256 internal constant SET_SUBSCRIBE = 0x01;
uint8 internal constant TICK_LOWER_OFFSET = 8;
uint8 internal constant TICK_UPPER_OFFSET = 32;
/// @dev This poolId is NOT compatible with the poolId used in UniswapV4 core. It is truncated to 25 bytes, and just used to lookup PoolKey in the poolKeys mapping.
function poolId(PositionInfo info) internal pure returns (bytes25 _poolId) {
assembly ("memory-safe") {
_poolId := and(MASK_UPPER_200_BITS, info)
}
}
function tickLower(PositionInfo info) internal pure returns (int24 _tickLower) {
assembly ("memory-safe") {
_tickLower := signextend(2, shr(TICK_LOWER_OFFSET, info))
}
}
function tickUpper(PositionInfo info) internal pure returns (int24 _tickUpper) {
assembly ("memory-safe") {
_tickUpper := signextend(2, shr(TICK_UPPER_OFFSET, info))
}
}
function hasSubscriber(PositionInfo info) internal pure returns (bool _hasSubscriber) {
assembly ("memory-safe") {
_hasSubscriber := and(MASK_8_BITS, info)
}
}
/// @dev this does not actually set any storage
function setSubscribe(PositionInfo info) internal pure returns (PositionInfo _info) {
assembly ("memory-safe") {
_info := or(info, SET_SUBSCRIBE)
}
}
/// @dev this does not actually set any storage
function setUnsubscribe(PositionInfo info) internal pure returns (PositionInfo _info) {
assembly ("memory-safe") {
_info := and(info, SET_UNSUBSCRIBE)
}
}
/// @notice Creates the default PositionInfo struct
/// @dev Called when minting a new position
/// @param _poolKey the pool key of the position
/// @param _tickLower the lower tick of the position
/// @param _tickUpper the upper tick of the position
/// @return info packed position info, with the truncated poolId and the hasSubscriber flag set to false
function initialize(PoolKey memory _poolKey, int24 _tickLower, int24 _tickUpper)
internal
pure
returns (PositionInfo info)
{
bytes25 _poolId = bytes25(PoolId.unwrap(_poolKey.toId()));
assembly {
info :=
or(
or(and(MASK_UPPER_200_BITS, _poolId), shl(TICK_UPPER_OFFSET, and(MASK_24_BITS, _tickUpper))),
shl(TICK_LOWER_OFFSET, and(MASK_24_BITS, _tickLower))
)
}
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none",
"useLiteralContent": false
},
"optimizer": {
"runs": 1,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@uniswap/v4-core/=lib/v4-core/",
"@uniswap/v4-periphery/=lib/v4-periphery/",
"@layerzerolabs/lz-evm-protocol-v2/=lib/LayerZero-v2/packages/layerzero-v2/evm/protocol/",
"@layerzerolabs/lz-evm-messagelib-v2/=lib/LayerZero-v2/packages/layerzero-v2/evm/messagelib/",
"@layerzerolabs/oapp-evm/=lib/LayerZero-v2/packages/layerzero-v2/evm/oapp/",
"@layerzerolabs/oapp-evm-devtools/=lib/devtools/packages/oapp-evm/",
"@layerzerolabs/oft-evm/=lib/devtools/packages/oft-evm/",
"@layerzerolabs/ovault-evm/=lib/devtools/packages/ovault-evm/",
"@layerzerolabs/test-devtools-evm-foundry/=lib/devtools/packages/test-devtools-evm-foundry/",
"solidity-bytes-utils/=lib/solidity-bytes-utils/",
"solady/=lib/solady/src/",
"@perimetersec/fuzzlib/=lib/fuzzlib/",
"solmate/=lib/solmate/",
"@safe-global/safe-smart-account/=lib/safe-smart-account/",
"@chainlink/contracts/=node_modules/@chainlink/contracts/",
"@SKYBITDev3/=node_modules/@SKYBITDev3/",
"@Vectorized/=node_modules/@Vectorized/",
"@arbitrum/=node_modules/@arbitrum/",
"@axelar-network/=node_modules/@axelar-network/",
"@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
"@eth-optimism/=node_modules/@eth-optimism/",
"@offchainlabs/=node_modules/@offchainlabs/",
"@scroll-tech/=node_modules/@scroll-tech/",
"@transmissions11/=node_modules/@transmissions11/",
"@zksync/=node_modules/@zksync/",
"LayerZero-v2/=lib/LayerZero-v2/",
"devtools/=lib/devtools/packages/toolbox-foundry/src/",
"ds-test/=lib/solmate/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
"forge-std/=lib/forge-std/src/",
"fuzzlib/=lib/fuzzlib/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"hardhat/=lib/v4-core/node_modules/hardhat/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"permit2/=lib/v4-periphery/lib/permit2/",
"safe-smart-account/=lib/safe-smart-account/",
"v4-core/=lib/v4-core/src/",
"v4-periphery/=lib/v4-periphery/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.