Verified contractPartialUNLICENSED
Opening
Address0xe0a7ca57c90d541d35e6acc0da68e1e9602a35c8
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.38
- Same code
Only this contract
Details
- Compiler
- solc 0.8.38+commit.1835d247
- Language
- solidity
- Optimization
- Yes, 1,000,000 runs
- EVM version
- cancun
- License
- UNLICENSED
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,484,916
- Creation transaction
- 0x30c29b37d1…39ba9a5600
- Libraries
- src/libraries/Money.sol:Money0x2d60…6d5ce1src/libraries/Waits.sol:Waits0xc87e…116477src/libraries/Orders.sol:Orders0x841e…0f9a33src/libraries/Opening.sol:Opening0xe0a7…2a35c8src/libraries/Curation.sol:Curation0x2d1d…424f27src/libraries/Swapping.sol:Swapping0xe780…9c8e9d
36 files
- src/libraries/Opening.solmain7.83 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/Hashes.sol1.03 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol24.62 KB
- lib/uniswap-hooks/lib/v4-core/src/interfaces/IExtsload.sol1.02 KB
- lib/uniswap-hooks/lib/v4-core/src/interfaces/IExttload.sol699 B
- lib/uniswap-hooks/lib/v4-core/src/interfaces/IHooks.sol8.23 KB
- lib/uniswap-hooks/lib/v4-core/src/interfaces/IPoolManager.sol12.84 KB
- lib/uniswap-hooks/lib/v4-core/src/interfaces/IProtocolFees.sol2.49 KB
- lib/uniswap-hooks/lib/v4-core/src/interfaces/external/IERC20Minimal.sol3.04 KB
- lib/uniswap-hooks/lib/v4-core/src/interfaces/external/IERC6909Claims.sol3.16 KB
- lib/uniswap-hooks/lib/v4-core/src/libraries/BitMath.sol2.61 KB
- lib/uniswap-hooks/lib/v4-core/src/libraries/CustomRevert.sol5.17 KB
- lib/uniswap-hooks/lib/v4-core/src/libraries/FixedPoint96.sol366 B
- lib/uniswap-hooks/lib/v4-core/src/libraries/FullMath.sol5.46 KB
- lib/uniswap-hooks/lib/v4-core/src/libraries/LPFeeLibrary.sol3.6 KB
- lib/uniswap-hooks/lib/v4-core/src/libraries/SafeCast.sol2.27 KB
- lib/uniswap-hooks/lib/v4-core/src/libraries/TickMath.sol12.38 KB
- lib/uniswap-hooks/lib/v4-core/src/types/BalanceDelta.sol2.34 KB
- lib/uniswap-hooks/lib/v4-core/src/types/BeforeSwapDelta.sol1.47 KB
- lib/uniswap-hooks/lib/v4-core/src/types/Currency.sol5.46 KB
- lib/uniswap-hooks/lib/v4-core/src/types/PoolId.sol539 B
- lib/uniswap-hooks/lib/v4-core/src/types/PoolKey.sol805 B
- lib/uniswap-hooks/lib/v4-core/src/types/PoolOperation.sol907 B
- src/interfaces/IMandate.sol11.89 KB
- src/interfaces/IReferencePrice.sol878 B
- src/interfaces/IStrategyRegistry.sol240 B
- src/libraries/Compass.sol4.25 KB
- src/libraries/FeeBook.sol4.3 KB
- src/libraries/FeeCurve.sol2.4 KB
- src/libraries/FeeSplit.sol2.12 KB
- src/libraries/Gate.sol3.78 KB
- src/libraries/Plugins.sol3.11 KB
- src/libraries/PoolMath.sol2.02 KB
- src/libraries/Price.sol2.11 KB
- src/libraries/Receipts.sol5.04 KB
- src/libraries/Store.sol9.53 KB
src/libraries/Opening.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.38;
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "@uniswap/v4-core/src/types/PoolId.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {LPFeeLibrary} from "@uniswap/v4-core/src/libraries/LPFeeLibrary.sol";
import {IMandate} from "../interfaces/IMandate.sol";
import {ISources} from "../interfaces/IReferencePrice.sol";
import {Store} from "./Store.sol";
import {Gate} from "./Gate.sol";
import {Plugins} from "./Plugins.sol";
import {Compass} from "./Compass.sol";
import {FeeBook} from "./FeeBook.sol";
import {PoolMath} from "./PoolMath.sol";
import {Price} from "./Price.sol";
import {Receipts} from "./Receipts.sol";
import {FeeCurve} from "./FeeCurve.sol";
import {FeeSplit} from "./FeeSplit.sol";
/// @title Opening
/// @notice OPEN: the curator opens a pool with settings that never change, at Chainlink's
/// price, with its first range around that price. Runs by DELEGATECALL from the hook.
library Opening {
using PoolIdLibrary for PoolKey;
/// @notice A curator fee is released over at least one day (a fee released at once cannot be clawed back).
uint256 internal constant MIN_VEST = 1 days;
/// @param manager the PoolManager the hook serves
/// @param sources the hook's approved list of price sources
/// @param key the pool; its hook must be this hook
/// @param settings the pool's settings, for ever
/// @param width the width of the first range in ticks
function open(
IPoolManager manager,
ISources sources,
PoolKey calldata key,
Store.Settings calldata settings,
int24 width
) external returns (PoolId id) {
// a swap-fee share needs its list: only openWith can name one
if (settings.shareBps != 0) revert IMandate.BadSplit();
return _open(manager, sources, key, settings, width);
}
/// @notice OPEN with lists: the same as `open`, and the pool may name a curator-fee split (the released
/// curator fee shared with the listed recipients) and a swap-fee share (`settings.shareBps` of every
/// swap fee, divided among the listed recipients). Both lists are fixed here, for ever.
function openWith(
IPoolManager manager,
ISources sources,
PoolKey calldata key,
Store.Settings calldata settings,
int24 width,
Store.Lists calldata lists
) external returns (PoolId id) {
if (!FeeSplit.valid(lists.splitTo, lists.splitBps, address(this))) revert IMandate.BadSplit();
if (!FeeSplit.valid(lists.shareTo, lists.shareBps, address(this))) revert IMandate.BadSplit();
// a slice needs someone to receive it, and a list needs a slice
if ((settings.shareBps == 0) != (lists.shareTo.length == 0)) revert IMandate.BadSplit();
id = _open(manager, sources, key, settings, width);
Store.Layout storage s = Store.store();
if (lists.splitTo.length != 0) {
s.splits[id].to = lists.splitTo;
s.splits[id].bps = lists.splitBps;
emit IMandate.SplitSet(id, lists.splitTo, lists.splitBps);
}
if (lists.shareTo.length != 0) {
s.shares[id].to = lists.shareTo;
s.shares[id].bps = lists.shareBps;
emit IMandate.ShareSet(id, settings.shareBps, lists.shareTo, lists.shareBps);
}
}
function _open(
IPoolManager manager,
ISources sources,
PoolKey calldata key,
Store.Settings calldata settings,
int24 width
) private returns (PoolId id) {
if (address(key.hooks) != address(this)) revert IMandate.WrongHook();
id = key.toId();
Store.Layout storage s = Store.store();
if (s.settings[id].curator != address(0)) revert IMandate.AlreadyOpen();
if (msg.sender != settings.curator) revert IMandate.NotCurator();
_check(key, settings);
if (!sources.isApproved(settings.source)) revert IMandate.SourceNotApproved();
// nobody chooses the starting price: it is Chainlink's, or the pool does not open
(bool live, uint160 sqrtPriceX96) = Price.read(settings.source, key.currency0, key.currency1, settings.maxAge);
if (!live) revert IMandate.NoPrice();
int24 tick = TickMath.getTickAtSqrtPrice(sqrtPriceX96);
(int24 lower, int24 upper) = Compass.centre(tick, width, key.tickSpacing);
if (!Compass.inside(_bounds(settings), lower, upper, tick, key.tickSpacing)) revert IMandate.OutOfBounds();
s.settings[id] = settings;
Store.Book storage book = s.book[id];
book.lower = lower;
book.upper = upper;
book.marks = FeeBook.fresh();
book.lastRefTick = tick;
// v4 does not call a hook's own callbacks, so beforeInitialize (which refuses) is not asked here
manager.initialize(key, sqrtPriceX96);
emit IMandate.PoolOpened(id, settings.curator, settings.source, sqrtPriceX96, lower, upper);
}
function _check(PoolKey calldata key, Store.Settings calldata settings) private view {
// a changing-fee pool must bring a valid curve; a fixed-fee pool must bring none
if (LPFeeLibrary.isDynamicFee(key.fee)) {
if (!FeeCurve.valid(settings.feeBase, settings.feeCap) || !FeeCurve.validFlow(settings.flow)) {
revert IMandate.BadCurve();
}
} else if (settings.feeBase | settings.feeCap | settings.gapSlope | settings.moveSlope != 0 || settings.flow != 0) {
revert IMandate.BadCurve();
}
if (settings.feeCapBps > FeeBook.MAX_FEE_BPS) revert IMandate.FeeCapTooHigh();
if (settings.feeCapBps != 0 && settings.vestPeriod < MIN_VEST) revert IMandate.VestTooShort();
if (settings.maxAge == 0 || settings.maxAge > Price.MAX_PRICE_AGE) revert IMandate.BadMaxAge();
if (settings.capacity <= PoolMath.LOCKED_SHARES) revert IMandate.BadCapacity();
Compass.validate(_bounds(settings), key.tickSpacing);
Receipts.check(settings);
if (settings.standing > 1) revert IMandate.StandingOff();
if (settings.shareBps > FeeSplit.MAX_SHARE_BPS) revert IMandate.BadSplit();
// a named registry must list this curator; a named plug-in must be a contract
if (settings.registry != address(0) && !Plugins.listed(settings.registry, settings.curator)) {
revert IMandate.NotListed();
}
if (settings.plugin != address(0) && settings.plugin.code.length == 0) revert IMandate.BadPlugin();
Gate.check(settings);
}
/// @notice ADMIT: anyone records an account a LIST pool's root proves.
function admit(PoolKey calldata key, address account, bytes32[] calldata proof) external {
Gate.admit(key.toId(), account, proof);
}
/// @notice beforeAddLiquidity for liquidity added by anyone but the hook: a gated pool, and a pool whose registry
/// no longer lists its curator (close-only), take money only through JOIN. The hook sees only the router
/// here, never the person, so no gate can be asked about them.
function outside(PoolKey calldata key) external view {
Store.Settings storage set = Store.store().settings[key.toId()];
if (set.gate != Gate.NONE) revert IMandate.OutsideLiquidity();
if (set.registry != address(0) && !Plugins.listed(set.registry, set.curator)) revert IMandate.OutsideLiquidity();
}
function _bounds(Store.Settings calldata settings) private pure returns (Compass.Bounds memory) {
return Compass.Bounds(settings.widthMin, settings.widthMax, settings.offsetMax);
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/Hashes.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/cryptography/Hashes.sol)
pragma solidity ^0.8.20;
/**
* @dev Library of standard hash functions.
*
* _Available since v5.1._
*/
library Hashes {
/**
* @dev Commutative Keccak256 hash of a sorted pair of bytes32. Frequently used when working with merkle proofs.
*
* NOTE: Equivalent to the `standardNodeHash` in our https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
*/
function commutativeKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32) {
return a < b ? efficientKeccak256(a, b) : efficientKeccak256(b, a);
}
/**
* @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
*/
function efficientKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32 value) {
assembly ("memory-safe") {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/cryptography/MerkleProof.sol)
// This file was procedurally generated from scripts/generate/templates/MerkleProof.js.
pragma solidity ^0.8.20;
import {Hashes} from "./Hashes.sol";
/**
* @dev These functions deal with verification of Merkle Tree proofs.
*
* The tree and the proofs can be generated using our
* https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
* You will find a quickstart guide in the readme.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the Merkle tree could be reinterpreted as a leaf value.
* OpenZeppelin's JavaScript library generates Merkle trees that are safe
* against this attack out of the box.
*
* IMPORTANT: Consider memory side-effects when using custom hashing functions
* that access memory in an unsafe way.
*
* NOTE: This library supports proof verification for merkle trees built using
* custom _commutative_ hashing functions (i.e. `H(a, b) == H(b, a)`). Proving
* leaf inclusion in trees built using non-commutative hashing functions requires
* additional logic that is not supported by this library.
*/
library MerkleProof {
/**
* @dev The multiproof provided is not valid.
*/
error MerkleProofInvalidMultiproof();
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in memory with the default hashing function.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in memory with the default hashing function.
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in memory with a custom hashing function.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processProof(proof, leaf, hasher) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in memory with a custom hashing function.
*/
function processProof(
bytes32[] memory proof,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = hasher(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with the default hashing function.
*/
function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProofCalldata(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with the default hashing function.
*/
function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with a custom hashing function.
*/
function verifyCalldata(
bytes32[] calldata proof,
bytes32 root,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processProofCalldata(proof, leaf, hasher) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with a custom hashing function.
*/
function processProofCalldata(
bytes32[] calldata proof,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = hasher(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in memory with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProof}.
*/
function multiProofVerify(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProof(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in memory with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
if (proofFlagsLen > 0) {
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = Hashes.commutativeKeccak256(a, b);
}
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in memory with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProof}.
*/
function multiProofVerify(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processMultiProof(proof, proofFlags, leaves, hasher) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in memory with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
if (proofFlagsLen > 0) {
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = hasher(a, b);
}
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in calldata with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProofCalldata}.
*/
function multiProofVerifyCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in calldata with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
if (proofFlagsLen > 0) {
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = Hashes.commutativeKeccak256(a, b);
}
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in calldata with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProofCalldata}.
*/
function multiProofVerifyCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves, hasher) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in calldata with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
if (proofFlagsLen > 0) {
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = hasher(a, b);
}
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
}
lib/uniswap-hooks/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/uniswap-hooks/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/uniswap-hooks/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/uniswap-hooks/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/uniswap-hooks/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/uniswap-hooks/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/uniswap-hooks/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/uniswap-hooks/lib/v4-core/src/libraries/BitMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
/// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol)
library BitMath {
/// @notice Returns the index of the most significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the most significant bit, must be greater than 0
/// @return r the index of the most significant bit
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020500060203020504000106050205030304010505030400000000))
}
}
/// @notice Returns the index of the least significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the least significant bit, must be greater than 0
/// @return r the index of the least significant bit
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
// Isolate the least significant bit.
x := and(x, sub(0, x))
// For the upper 3 bits of the result, use a De Bruijn-like lookup.
// Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
// forgefmt: disable-next-item
r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
0x8040405543005266443200005020610674053026020000107506200176117077)))
// For the lower 5 bits of the result, use a De Bruijn lookup.
// forgefmt: disable-next-item
r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
}
}
}
lib/uniswap-hooks/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/uniswap-hooks/lib/v4-core/src/libraries/FixedPoint96.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
lib/uniswap-hooks/lib/v4-core/src/libraries/FullMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0 = a * b; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
assembly ("memory-safe") {
result := div(prod0, denominator)
}
return result;
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly ("memory-safe") {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly ("memory-safe") {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = (0 - denominator) & denominator;
// Divide denominator by power of two
assembly ("memory-safe") {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly ("memory-safe") {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly ("memory-safe") {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the preconditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) != 0) {
require(++result > 0);
}
}
}
}
lib/uniswap-hooks/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/uniswap-hooks/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/uniswap-hooks/lib/v4-core/src/libraries/TickMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {BitMath} from "./BitMath.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
using CustomRevert for bytes4;
/// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK
error InvalidTick(int24 tick);
/// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK
error InvalidSqrtPrice(uint160 sqrtPriceX96);
/// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MAX_TICK = 887272;
/// @dev The minimum tick spacing value drawn from the range of type int16 that is greater than 0, i.e. min from the range [1, 32767]
int24 internal constant MIN_TICK_SPACING = 1;
/// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767]
int24 internal constant MAX_TICK_SPACING = type(int16).max;
/// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_PRICE = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
/// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1`
uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE =
1461446703485210103287273052203988822378723970342 - 4295128739 - 1;
/// @notice Given a tickSpacing, compute the maximum usable tick
function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MAX_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Given a tickSpacing, compute the minimum usable tick
function minUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MIN_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0)
/// at the given tick
function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
unchecked {
uint256 absTick;
assembly ("memory-safe") {
tick := signextend(2, tick)
// mask = 0 if tick >= 0 else -1 (all 1s)
let mask := sar(255, tick)
// if tick >= 0, |tick| = tick = 0 ^ tick
// if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)
// either way, |tick| = mask ^ (tick + mask)
absTick := xor(mask, add(mask, tick))
}
if (absTick > uint256(int256(MAX_TICK))) InvalidTick.selector.revertWith(tick);
// The tick is decomposed into bits, and for each bit with index i that is set, the product of 1/sqrt(1.0001^(2^i))
// is calculated (using Q128.128). The constants used for this calculation are rounded to the nearest integer
// Equivalent to:
// price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
// or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128
uint256 price;
assembly ("memory-safe") {
price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1)))
}
if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128;
assembly ("memory-safe") {
// if (tick > 0) price = type(uint256).max / price;
if sgt(tick, 0) { price := div(not(0), price) }
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtPrice of the output price is always consistent
// `sub(shl(32, 1), 1)` is `type(uint32).max`
// `price + type(uint32).max` will not overflow because `price` fits in 192 bits
sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1)))
}
}
}
/// @notice Calculates the greatest tick value such that getSqrtPriceAtTick(tick) <= sqrtPriceX96
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getSqrtPriceAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the getSqrtPriceAtTick(tick) is less than or equal to the input sqrtPriceX96
function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
unchecked {
// Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice();
// second inequality must be >= because the price can never reach the price at the max tick
// if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true
// if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1
if ((sqrtPriceX96 - MIN_SQRT_PRICE) > MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) {
InvalidSqrtPrice.selector.revertWith(sqrtPriceX96);
}
uint256 price = uint256(sqrtPriceX96) << 32;
uint256 r = price;
uint256 msb = BitMath.mostSignificantBit(r);
if (msb >= 128) r = price >> (msb - 127);
else r = price << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // Q22.128 number
// Magic number represents the ceiling of the maximum value of the error when approximating log_sqrt10001(x)
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
// Magic number represents the minimum value of the error when approximating log_sqrt10001(x), when
// sqrtPrice is from the range (2^-64, 2^64). This is safe as MIN_SQRT_PRICE is more than 2^-64. If MIN_SQRT_PRICE
// is changed, this may need to be changed too
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
}
lib/uniswap-hooks/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/uniswap-hooks/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/uniswap-hooks/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/uniswap-hooks/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/uniswap-hooks/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/uniswap-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;
}
src/interfaces/IMandate.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.38;
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
/// @title IMandate
/// @notice Every event and error of the hook and of its libraries, in one place. The libraries run by
/// DELEGATECALL, so their logs come from the hook's address; a front end or a subgraph decodes
/// them with this interface.
interface IMandate {
// ---- the share ledger (ERC-6909 shapes; the id of a pool's shares is its pool id) ----
/// @param caller the account that acted (never the PoolManager, also for a mint or burn inside an unlock)
event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);
event OperatorSet(address indexed owner, address indexed operator, bool approved);
error InsufficientBalance();
error InsufficientAllowance();
/// @notice An action of the hook is running: transfers and value views wait until it is over.
error Locked();
// ---- OPEN ----
/// @notice A pool was opened at Chainlink's price with its first range. Its settings never change.
event PoolOpened(
PoolId indexed id, address indexed curator, address source, uint160 sqrtPriceX96, int24 lower, int24 upper
);
/// @notice The pool's fee split: who shares its released curator fee, in basis points of that fee. Set at OPEN, for ever.
event SplitSet(PoolId indexed id, address[] to, uint16[] bps);
/// @notice A split list is not allowed (more than eight, a zero address, the hook itself, a zero share, or a total above 10,000).
error BadSplit();
/// @notice The pool key names another hook.
error WrongHook();
error AlreadyOpen();
/// @notice Only the curator named in the settings may open the pool.
error NotCurator();
/// @notice The curator fee cap is above 20%.
error FeeCapTooHigh();
/// @notice A pool with a curator fee must vest it over at least one day.
error VestTooShort();
/// @notice maxAge must be between 1 second and 259,200 seconds.
error BadMaxAge();
/// @notice The capacity must be above the shares the first deposit locks.
error BadCapacity();
/// @notice The price source is not on the hook's approved list.
error SourceNotApproved();
/// @notice The source has no live Chainlink price for the pair.
error NoPrice();
/// @notice The range is not inside the pool's bounds around Chainlink's price.
error OutOfBounds();
/// @notice A changing-fee pool needs a curve with base <= cap <= 1%; a fixed-fee pool must have none.
error BadCurve();
/// @notice A pool on this hook starts through OPEN only, never by a direct call to the PoolManager.
error NotThroughOpen();
// ---- JOIN ----
/// @notice `payer` paid `amount0` and `amount1` and `to` received `shares` of the pool.
event Joined(
PoolId indexed id, address indexed payer, address indexed to, uint256 shares, uint256 amount0, uint256 amount1
);
/// @notice Swap fees the range earned were moved into idle, where every share owns its slice.
event FeesCollected(PoolId indexed id, uint256 amount0, uint256 amount1);
/// @notice No pool with this exact key was opened on this hook.
error UnknownPool();
/// @notice The caller's deadline has passed.
error Expired();
/// @notice The shares would go to the zero address.
error BadRecipient();
/// @notice The price moved past the caller's limit (the most to pay on a JOIN, the least to get on an exit).
error Slippage();
/// @notice The action would move no tokens: a share is never free.
error NothingPaid();
/// @notice The first deposit must be more than the 1,000 shares it locks, and fit in 128 bits.
error BadFirstDeposit();
/// @notice The pool is at its capacity.
error OverCapacity();
/// @notice Less arrived than was asked: a token that keeps a fee on transfer is refused.
error ShortPayment();
/// @notice The caller would not take back the ETH it sent and the verb did not spend.
error RefundFailed();
error BadAction();
// ---- SETTLE UP ----
/// @notice Unreleased curator fee shares were burned because the value ratio fell: they go back to the providers.
event Clawback(PoolId indexed id, uint256 shares, uint256 ratio);
/// @notice Curator fee shares that time has earned were released to the curator.
event Vested(PoolId indexed id, address indexed curator, uint256 shares);
/// @notice New curator fee shares were minted for a gain above the high-water mark. They are unreleased.
event CuratorFee(PoolId indexed id, uint256 shares, uint256 ratio);
// ---- the exit (LEAVE) ----
/// @notice `owner` burned `shares` and `to` received their slice of the range and of idle, in kind.
event Exited(
PoolId indexed id, address indexed owner, address indexed to, uint256 shares, uint256 amount0, uint256 amount1
);
/// @notice An exit went through although SETTLE UP failed inside it. Nothing may stop an exit; this says it happened.
event SettleSkipped(PoolId indexed id);
// ---- STEER ----
/// @notice The range moved, by the rule (from the first swap of a block) or by the curator's signed range.
event Moved(PoolId indexed id, int24 lower, int24 upper, bool bySignature);
/// @notice The rule could not move the range; the swap went on with the old one. `reason` is the error's selector.
event RecentreSkipped(PoolId indexed id, bytes4 reason);
/// @notice The pool's own price is too far from Chainlink's to move the range safely.
error PoolPriceOff();
/// @notice The range already moved in this block.
error AlreadyMoved();
/// @notice The signature is not the curator's over this pool, range, nonce and deadline.
error BadSignature();
/// @notice A signed range names another sender (audit A6).
error NotSender();
// ---- limit orders ----
event OrderPlaced(PoolId indexed id, address indexed owner, int24 tick, bool zeroForOne, uint256 epoch, uint128 liquidity);
event OrderCancelled(PoolId indexed id, address indexed owner, int24 tick, bool zeroForOne, uint256 epoch);
event OrderFilled(PoolId indexed id, int24 tick, bool zeroForOne, uint256 epoch, uint256 amount0, uint256 amount1);
event OrderTaken(
PoolId indexed id, address indexed owner, int24 tick, bool zeroForOne, uint256 epoch, uint256 amount0, uint256 amount1
);
/// @notice Filling the orders a swap crossed failed; the swap went through and the orders stay cancellable.
event FillSkipped(PoolId indexed id, bytes4 reason);
/// @notice An order must be on the tick grid, on the far side of the price, and not empty.
error BadOrder();
/// @notice The caller has no order there (or, for a take, the bucket is not filled).
error NoOrder();
// ---- waiting swaps ----
event Waiting(PoolId indexed id, uint256 indexed number, address indexed owner, bool zeroForOne, uint256 amount);
/// @notice The limit and the expiry of a wait parked with either (emitted after its Waiting).
event WaitTerms(PoolId indexed id, uint256 indexed number, uint160 limit, uint40 expiry);
event TakenBack(PoolId indexed id, uint256 indexed number, address indexed owner, uint256 left, uint256 got);
/// @notice URC-2 (the shape of OpenZeppelin uniswap-hooks' IHookEvents): a swap, or part of one, that the
/// hook filled itself from waiting swaps. The amounts are the swapper's; the fee went to the providers.
event HookSwap(
bytes32 indexed poolId,
address indexed sender,
int128 amount0,
int128 amount1,
uint128 hookLPfeeAmount0,
uint128 hookLPfeeAmount1
);
/// @notice Matching against waiting swaps failed; the swap went on against the pool alone.
event MatchSkipped(PoolId indexed id, bytes4 reason);
// ---- RECEIPTS ----
/// @notice A swap named `payee` and `orderRef`: one receipt, with the swapper's whole delta (negative = paid in).
event Receipt(
bytes32 indexed receiptId,
PoolId indexed id,
address indexed payee,
bytes32 orderRef,
address payer,
address sender,
int128 amount0,
int128 amount1
);
/// @notice Receipt data came and no receipt was written; the swap went through. 1 malformed, 2 the payee rule
/// said no, 3 already written.
event ReceiptRefused(PoolId indexed id, address indexed sender, uint8 reason);
/// @notice The receipt settings at OPEN do not hang together.
error BadReceipts();
// ---- SWITCH ----
/// @notice `owner` left pool `from` and joined pool `to` in one go; `back0` and `back1` came back to them.
event Switched(PoolId indexed from, PoolId indexed to, address indexed owner, uint256 back0, uint256 back1);
/// @notice SWITCH works between two pools of the same pair only.
error NotSamePair();
// ---- swap-fee share ----
/// @notice A pool's swap-fee share list, set once at OPEN: `slice` bps of every fee, divided by `bps` (of the slice).
event ShareSet(PoolId indexed id, uint16 slice, address[] to, uint16[] bps);
/// @notice A collect credited `recipient` its part of the slice. Nothing was sent.
event ShareCredited(PoolId indexed id, address indexed recipient, uint256 amount0, uint256 amount1);
/// @notice `recipient` took what it was owed.
event ShareClaimed(PoolId indexed id, address indexed recipient, uint256 amount0, uint256 amount1);
// ---- standing orders ----
/// @notice A provider's standing order ran: `shares` withdrawn, the keeper paid the tip.
event OrderRun(
PoolId indexed id, address indexed owner, bytes32 orderHash, uint8 kind, uint256 shares, uint256 tip0, uint256 tip1, address indexed keeper
);
/// @notice Every order `owner` signed before `epoch` is dead.
event OrdersCancelled(address indexed owner, uint64 epoch);
/// @notice The pool does not take standing orders, or OPEN was given a value other than 0 or 1.
error StandingOff();
/// @notice The order was cancelled, killed by a transfer, or already ran.
error StaleOrder();
/// @notice The tip is above 20 basis points.
error TipTooHigh();
/// @notice Chainlink's price has not crossed the trigger.
error NotTriggered();
// ---- strategy registry and plug-in ----
/// @notice OPEN: the pool's registry does not list its curator (or is not a registry at all).
error NotListed();
/// @notice JOIN: the registry no longer lists the curator; the pool takes no new money. Exits are untouched.
error CloseOnly();
/// @notice OPEN: the plug-in has no code.
error BadPlugin();
/// @notice The caller sent too little gas for the plug-in's full allowance; send more and the action goes through.
error PluginGas();
/// @notice The plug-in reverted, ran out of its gas or tried to re-enter; the action went through without it.
event PluginSkipped(PoolId indexed id, uint8 what);
// ---- the gate ----
/// @notice A LIST pool admitted an account (it may now hold new shares).
event Admitted(PoolId indexed id, address indexed account);
/// @notice OPEN: a gate kind above 2, or the fields that kind needs missing or extra. ADMIT: the pool has no LIST gate.
error BadGate();
/// @notice ADMIT: the proof does not show this account under the root, or holds a zero element.
error BadProof();
/// @notice JOIN: the account that would hold the shares is not let in by the pool's gate.
error NotAllowed();
/// @notice A gated or close-only pool takes liquidity only through JOIN.
error OutsideLiquidity();
}
src/interfaces/IReferencePrice.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.38;
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
/// @title IReferencePrice
/// @notice The one question the hook asks about prices (the written design plan, part C).
/// A source answers from Chainlink; the hook never learns which feed or which kind of feed.
interface IReferencePrice {
/// @return sqrtPriceX96 the price of currency0 in currency1 as a Q64.96 square root (0 means no price)
/// @return updatedAt when that price was set
function price(Currency currency0, Currency currency1)
external
view
returns (uint160 sqrtPriceX96, uint256 updatedAt);
}
/// @title ISources
/// @notice The add-only list of price sources a pool may name when it opens.
interface ISources {
function isApproved(address source) external view returns (bool);
}
src/interfaces/IStrategyRegistry.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.38;
/// @notice What a pool's strategy registry answers: does it list `curator`.
interface IStrategyRegistry {
function listed(address curator) external view returns (bool);
}
src/libraries/Compass.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.38;
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
/// @title Compass
/// @notice Where a pool's range may be. The bounds are chosen when the pool opens and never change;
/// nothing a strategy or a curator answers can put the range outside them.
/// @dev All numbers are ticks. A range's centre is `lower + width / 2`. The reference tick is Chainlink's.
library Compass {
/// @param widthMin the narrowest the range may be
/// @param widthMax the widest the range may be
/// @param offsetMax how far the range's centre may be from the reference tick
struct Bounds {
int24 widthMin;
int24 widthMax;
int24 offsetMax;
}
error BadBounds();
/// @notice The lowest and highest ticks a pool of this spacing can use.
function usable(int24 spacing) internal pure returns (int24 low, int24 high) {
low = TickMath.minUsableTick(spacing);
high = TickMath.maxUsableTick(spacing);
}
/// @notice Refuses bounds that make no sense: widths are multiples of the spacing with
/// 0 < widthMin <= widthMax; the offset is at least one spacing (so a centred range always
/// fits after rounding to the spacing) and below half the narrowest width (so the reference
/// price is always inside the range).
function validate(Bounds memory b, int24 spacing) internal pure {
(int24 low, int24 high) = usable(spacing);
if (
b.widthMin <= 0 || b.widthMin > b.widthMax || b.widthMin % spacing != 0 || b.widthMax % spacing != 0
|| b.widthMax > high - low || b.offsetMax < spacing || 2 * b.offsetMax >= b.widthMin
) revert BadBounds();
}
/// @notice The range of `width` ticks centred on the reference tick, on the pool's tick grid.
function centre(int24 refTick, int24 width, int24 spacing) internal pure returns (int24 lower, int24 upper) {
lower = _floor(int256(refTick) - width / 2, spacing);
upper = lower + width;
}
/// @notice True when a range is on the grid, usable, and inside the bounds around the reference tick.
function inside(Bounds memory b, int24 lower, int24 upper, int24 refTick, int24 spacing)
internal
pure
returns (bool)
{
(int24 low, int24 high) = usable(spacing);
if (lower >= upper || lower < low || upper > high) return false;
if (lower % spacing != 0 || upper % spacing != 0) return false;
int256 width = int256(upper) - lower;
if (width < b.widthMin || width > b.widthMax) return false;
int256 offset = int256(lower) + width / 2 - refTick;
if (offset < 0) offset = -offset;
return offset <= b.offsetMax;
}
/// @notice Squeezes ANY answer (a strategy's, a curator's) into the bounds: the width is clamped
/// between widthMin and widthMax, the centre is clamped to within offsetMax of the reference.
/// @dev The result is `inside` whenever the reference tick is far enough from the ends of the tick range.
function squeeze(Bounds memory b, int24 lower, int24 upper, int24 refTick, int24 spacing)
internal
pure
returns (int24 newLower, int24 newUpper)
{
int256 width = int256(upper) - lower;
int256 mid = int256(lower) + width / 2;
width = (width / spacing) * spacing;
if (width < b.widthMin) width = b.widthMin;
if (width > b.widthMax) width = b.widthMax;
// rounding down to the grid moves the centre down by less than one spacing: leave room for it
int256 lowest = int256(refTick) - b.offsetMax + spacing - 1;
int256 highest = int256(refTick) + b.offsetMax;
if (mid < lowest) mid = lowest;
if (mid > highest) mid = highest;
newLower = _floor(mid - width / 2, spacing);
newUpper = newLower + int24(width);
}
/// @dev Rounds down to the tick grid (towards minus infinity, also for negative ticks).
function _floor(int256 tick, int24 spacing) private pure returns (int24) {
int256 q = tick / spacing;
if (tick % spacing < 0) q -= 1;
return int24(q * spacing);
}
}
src/libraries/FeeBook.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.38;
import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
/// @title FeeBook
/// @notice The maths of SETTLE UP (the written design plan, section 4): CLAWBACK, then VEST, then FEE.
/// Pure: it works on a copy of a pool's marks and says how many fee shares to burn, release and mint.
/// @dev Every rounding is for the providers: a fee and a release round down, a clawback rounds up.
library FeeBook {
/// @notice The scale of a value ratio (1e18 is "exactly what doing nothing would hold").
uint256 internal constant ONE = 1e18;
uint256 internal constant BPS = 10_000;
/// @notice The most a curator may ever take of a gain: 20%.
uint256 internal constant MAX_FEE_BPS = 2_000;
/// @param hwm the high-water mark: the best value ratio so far. A fee is paid only above it. It never falls.
/// @param clawBase the bottom of the clawback window: the mark where the oldest unreleased fee started.
/// @param clawTop the top of the window: the ratio at the last fee, lowered by each clawback.
/// @param unvested the curator's fee shares that are not released yet.
/// @param vestLast when vesting was last counted.
/// @param vestEnd when everything unreleased is released.
struct Marks {
uint256 hwm;
uint256 clawBase;
uint256 clawTop;
uint256 unvested;
uint64 vestLast;
uint64 vestEnd;
}
/// @notice The marks of a pool nobody has joined yet.
function fresh() internal pure returns (Marks memory m) {
m.hwm = ONE;
m.clawBase = ONE;
m.clawTop = ONE;
}
/// @notice CLAWBACK: the unreleased fee shares to burn because the ratio fell inside the window.
function clawback(Marks memory m, uint256 ratio) internal pure returns (uint256 burned) {
if (m.unvested == 0 || ratio >= m.clawTop) return 0;
if (ratio <= m.clawBase) {
burned = m.unvested;
m.clawTop = m.clawBase;
} else {
// in proportion between the top and the bottom, rounded up; below unvested because ratio > clawBase
burned = FullMath.mulDivRoundingUp(m.unvested, m.clawTop - ratio, m.clawTop - m.clawBase);
m.clawTop = ratio; // this fall is now paid for: the same dip is never charged twice
}
m.unvested -= burned;
}
/// @notice VEST: the unreleased fee shares that time has earned.
function vest(Marks memory m, uint256 time) internal pure returns (uint256 released) {
if (m.unvested == 0 || time <= m.vestLast) return 0;
if (time >= m.vestEnd) {
released = m.unvested;
} else {
released = FullMath.mulDiv(m.unvested, time - m.vestLast, m.vestEnd - m.vestLast);
}
m.unvested -= released;
m.vestLast = uint64(time);
}
/// @notice FEE: the new fee shares for a ratio above the mark, at most `capBps` of the gain.
function fee(Marks memory m, uint256 ratio, uint256 supply, uint256 capBps, uint256 time, uint256 vestPeriod)
internal
pure
returns (uint256 minted)
{
if (ratio <= m.hwm) return 0;
// shares x cap x gain / (10,000 x ratio), rounded down twice: worth at most cap of the gain
minted = FullMath.mulDiv(FullMath.mulDiv(supply, capBps, BPS), ratio - m.hwm, ratio);
// the window's bottom moves only when nothing is unreleased, so a later fee never shortens
// the window of an earlier one
if (m.unvested == 0) m.clawBase = m.hwm;
m.hwm = ratio;
m.clawTop = ratio;
if (minted != 0) {
m.unvested += minted;
m.vestLast = uint64(time);
m.vestEnd = uint64(time + vestPeriod);
}
}
/// @notice SETTLE UP, in the one order the design allows. `supply` is the share supply before it.
function settle(Marks memory m, uint256 ratio, uint256 supply, uint256 capBps, uint256 time, uint256 vestPeriod)
internal
pure
returns (uint256 burned, uint256 released, uint256 minted)
{
burned = clawback(m, ratio);
released = vest(m, time);
minted = fee(m, ratio, supply - burned, capBps, time, vestPeriod);
}
}
src/libraries/FeeCurve.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.38;
/// @title FeeCurve
/// @notice The swap fee of a changing-fee pool: fee = min(cap, base + gap x gapSlope + move x moveSlope).
/// gap is the distance in ticks between the pool's price and Chainlink's; move is how many ticks
/// Chainlink's price moved since the hook last looked. Pure, and nothing a swapper sends lowers it.
library FeeCurve {
/// @notice The most any pool on this hook may ever charge a swap: 1% (in pips).
uint24 internal constant MAX_SWAP_FEE = 10_000;
/// @notice Which swaps pay the gap term, fixed at OPEN: every swap, only a swap that moves the pool
/// further from Chainlink's price, or only a swap that moves it back toward it.
uint8 internal constant BOTH = 0;
uint8 internal constant AWAY = 1;
uint8 internal constant TOWARD = 2;
function validFlow(uint8 flow) internal pure returns (bool) {
return flow <= TOWARD;
}
/// @notice The gap this swap pays, in ticks. The side is known before the swap from the sign of
/// (spot - ref) and the swap's direction: above Chainlink's price a oneForZero swap (tick up) moves
/// AWAY and a zeroForOne swap moves TOWARD; below it, the reverse. A swap that starts toward and
/// would overshoot is still toward. Outside the pool's direction the gap is 0.
function gap(uint8 flow, int24 spot, int24 ref, bool zeroForOne) internal pure returns (uint256) {
if (spot == ref) return 0;
uint256 d = spot > ref ? uint256(int256(spot) - ref) : uint256(int256(ref) - spot);
if (flow == BOTH) return d;
bool away = (spot > ref) != zeroForOne;
return (flow == AWAY) == away ? d : 0;
}
/// @notice A pool with no curve has a cap of zero. A curve needs base <= cap <= MAX_SWAP_FEE.
function valid(uint24 base, uint24 cap) internal pure returns (bool) {
return cap != 0 && base <= cap && cap <= MAX_SWAP_FEE;
}
function lpFee(uint24 base, uint24 cap, uint24 gapSlope, uint24 moveSlope, uint256 gapTicks, uint256 moveTicks)
internal
pure
returns (uint24)
{
// ticks are below 2^21 and slopes below 2^24: the sum cannot overflow
uint256 fee = uint256(base) + gapTicks * gapSlope + moveTicks * moveSlope;
return fee > cap ? cap : uint24(fee);
}
}
src/libraries/FeeSplit.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.38;
import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
/// @title FeeSplit
/// @notice The optional split of a released curator fee. Pure: it checks a list and divides an
/// amount. The listed recipients' shares add up to at most 100% of the fee, and the curator keeps the rest,
/// so a split never makes the fee bigger. Every division rounds down and what rounding leaves is the curator's.
library FeeSplit {
/// @notice The most recipients a pool may name besides its curator.
uint256 internal constant MAX_RECIPIENTS = 8;
/// @notice The largest slice of the swap fees a pool may give its share list: 3,000 bps, 30%.
uint16 internal constant MAX_SHARE_BPS = 3_000;
/// @notice 100% in basis points.
uint256 internal constant WHOLE = 10_000;
/// @notice Whether a list is allowed: the same length, at most eight, no zero address, no recipient that is
/// `hook` itself (shares sent there would never be released), every share above zero, a total of
/// at most 10,000. An empty list is allowed: the curator then gets the whole fee.
function valid(address[] memory to, uint16[] memory bps, address hook) internal pure returns (bool) {
if (to.length != bps.length || to.length > MAX_RECIPIENTS) return false;
uint256 total = 0;
for (uint256 i; i < to.length; ++i) {
if (to[i] == address(0) || to[i] == hook || bps[i] == 0) return false;
total += bps[i];
}
return total <= WHOLE;
}
/// @notice Divides `amount` by the list. `parts[i]` goes to recipient i, `rest` to the curator;
/// the parts and the rest always add up to `amount`.
function divide(uint256 amount, uint16[] memory bps) internal pure returns (uint256[] memory parts, uint256 rest) {
parts = new uint256[](bps.length);
rest = amount;
for (uint256 i; i < bps.length; ++i) {
parts[i] = FullMath.mulDiv(amount, bps[i], WHOLE);
rest -= parts[i];
}
}
}
src/libraries/Gate.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.38;
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import {IMandate} from "../interfaces/IMandate.sol";
import {Store} from "./Store.sol";
/// @notice What a VERIFIER gate is asked. A World credential registry is one such contract.
interface IGateVerifier {
function allowed(address account) external view returns (bool);
}
/// @title Gate
/// @notice Who may put money IN to a pool, fixed at OPEN. Asked only by JOIN (and SWITCH's join side)
/// about the account that will HOLD the shares, never by anything that takes money out.
library Gate {
uint8 internal constant NONE = 0;
/// @notice A Merkle root of allowed accounts; an account is admitted once with ADMIT and a proof.
uint8 internal constant LIST = 1;
/// @notice An outside contract asked allowed(account) on every JOIN.
uint8 internal constant VERIFIER = 2;
/// @notice The verifier's allowance for its one answer.
uint256 internal constant VERIFY_GAS = 30_000;
/// @notice OPEN's checks: the kind and exactly the fields that kind needs.
function check(Store.Settings calldata s) internal view {
bool ok = false; // a kind other than these three stays false
if (s.gate == NONE) ok = s.gateRoot == bytes32(0) && s.gateVerifier == address(0);
else if (s.gate == LIST) ok = s.gateRoot != bytes32(0) && s.gateVerifier == address(0);
else if (s.gate == VERIFIER) ok = s.gateRoot == bytes32(0) && s.gateVerifier.code.length != 0;
if (!ok) revert IMandate.BadGate();
}
/// @notice May `holder` receive new shares of the pool? NONE: yes. LIST: admitted. VERIFIER: asked now.
function allows(PoolId id, Store.Settings storage s, address holder) internal view returns (bool) {
uint8 kind = s.gate;
if (kind == NONE) return true;
if (kind == LIST) return Store.store().admitted[id][holder];
return verified(s.gateVerifier, holder);
}
/// @notice ADMIT: records `account` for a LIST pool when `proof` shows its leaf under the root. Anyone may send
/// it: a valid proof only admits the account it proves. The leaf is a hash of a hash of the account, so
/// an inner node of the tree can never pass for a leaf; a proof with a zero element is refused.
function admit(PoolId id, address account, bytes32[] calldata proof) internal {
Store.Settings storage s = Store.store().settings[id];
if (s.curator == address(0)) revert IMandate.UnknownPool();
if (s.gate != LIST) revert IMandate.BadGate();
for (uint256 i; i < proof.length; ++i) {
if (proof[i] == bytes32(0)) revert IMandate.BadProof();
}
bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(account))));
if (!MerkleProof.verifyCalldata(proof, s.gateRoot, leaf)) revert IMandate.BadProof();
Store.store().admitted[id][account] = true;
emit IMandate.Admitted(id, account);
}
/// @notice A capped STATICCALL; only the exact 32-byte word 1 is a yes. A revert, a burn of the allowance, a
/// wrong length or any other word is a no.
function verified(address verifier, address account) internal view returns (bool yes) {
bytes memory data = abi.encodeCall(IGateVerifier.allowed, (account));
uint256 gasCap = VERIFY_GAS;
assembly ("memory-safe") {
let ok := staticcall(gasCap, verifier, add(data, 0x20), mload(data), 0, 0)
if and(ok, eq(returndatasize(), 0x20)) {
returndatacopy(0, 0, 0x20)
yes := eq(mload(0), 1)
}
}
}
}
src/libraries/Plugins.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.38;
import {IStrategyRegistry} from "../interfaces/IStrategyRegistry.sol";
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
import {IMandate} from "../interfaces/IMandate.sol";
import {Store} from "./Store.sol";
/// @notice What a pool's plug-in is told. It answers nothing the hook reads.
interface IMandatePlugin {
/// @param what 1 JOIN (from = payer, to = holder), 2 LEAVE (from = owner, to = recipient), 3 TRANSFER (from, to)
function onMandate(PoolId id, uint8 what, address from, address to, uint256 shares) external;
}
/// @title Plugins
/// @notice The two outside contracts a pool may name at OPEN. Neither is ever asked on the way out:
/// a plug-in is told after the money has moved, with a fixed allowance of gas, and cannot stop anything;
/// a registry is asked only by OPEN and JOIN, so a removed curator makes the pool close-only.
library Plugins {
uint8 internal constant JOINED = 1;
uint8 internal constant LEFT = 2;
uint8 internal constant MOVED = 3;
/// @notice The plug-in's allowance for one notice.
uint256 internal constant PLUGIN_GAS = 100_000;
/// @notice The registry's allowance for its one answer.
uint256 internal constant READ_GAS = 30_000;
/// @dev The gas this library spends between its check and the call (cold account, memory), with room to spare.
uint256 private constant OVERHEAD = 5_000;
/// @notice Tells the pool's plug-in, if it has one. Reverts PluginGas when the caller sent too little gas for
/// the plug-in's whole allowance (63/64 of what is left must cover it), so a notice cannot be starved;
/// a plug-in that fails anyway is skipped with an event. No return data is copied.
function tell(PoolId id, uint8 what, address from, address to, uint256 shares) internal {
address plugin = Store.store().settings[id].plugin;
if (plugin == address(0)) return;
bytes memory data = abi.encodeCall(IMandatePlugin.onMandate, (id, what, from, to, shares));
if (gasleft() < PLUGIN_GAS + PLUGIN_GAS / 63 + OVERHEAD) revert IMandate.PluginGas();
uint256 gasCap = PLUGIN_GAS;
bool ok;
assembly ("memory-safe") {
ok := call(gasCap, plugin, 0, add(data, 0x20), mload(data), 0, 0)
}
if (!ok) emit IMandate.PluginSkipped(id, what);
}
/// @notice Does `registry` list `curator`: one staticcall capped at READ_GAS whose answer must be exactly the
/// word 1. A revert, no code, a short or odd answer all mean no.
function listed(address registry, address curator) internal view returns (bool yes) {
bytes memory data = abi.encodeCall(IStrategyRegistry.listed, (curator));
uint256 gasCap = READ_GAS;
assembly ("memory-safe") {
let ok := staticcall(gasCap, registry, add(data, 0x20), mload(data), 0, 0)
if and(ok, eq(returndatasize(), 0x20)) {
returndatacopy(0, 0, 0x20)
yes := eq(mload(0), 1)
}
}
}
}
src/libraries/PoolMath.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.38;
import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
import {FixedPoint96} from "@uniswap/v4-core/src/libraries/FixedPoint96.sol";
/// @title PoolMath
/// @notice The share maths of a pool. Every result rounds against whoever acts: a joiner pays
/// rounded up, a leaver is paid rounded down, so the rounding always stays with the pool.
library PoolMath {
/// @notice The shares the first deposit locks for ever (the inflation attack needs them gone).
uint256 internal constant LOCKED_SHARES = 1000;
/// @notice A value ratio of exactly one, and the scale of every ratio.
uint256 internal constant ONE = 1e18;
/// @notice What `shares` out of `supply` must pay of a bucket holding `amount`. Rounded up.
function costOf(uint256 amount, uint256 shares, uint256 supply) internal pure returns (uint256) {
return FullMath.mulDivRoundingUp(amount, shares, supply);
}
/// @notice What `shares` out of `supply` are owed of a bucket holding `amount`. Rounded down.
function payoutOf(uint256 amount, uint256 shares, uint256 supply) internal pure returns (uint256) {
return FullMath.mulDiv(amount, shares, supply);
}
/// @notice The worth of two amounts in token1 at a price given as a Q64.96 square root. Rounded down.
function valueOf(uint256 amount0, uint256 amount1, uint160 sqrtPriceX96) internal pure returns (uint256) {
uint256 half = FullMath.mulDiv(amount0, sqrtPriceX96, FixedPoint96.Q96);
return FullMath.mulDiv(half, sqrtPriceX96, FixedPoint96.Q96) + amount1;
}
/// @notice What the pool holds now over what it would hold had nobody done anything, scaled by ONE.
/// A pool with an empty hold basket has a ratio of exactly ONE.
function ratioOf(uint256 valueNow, uint256 valueHold) internal pure returns (uint256) {
if (valueHold == 0) return ONE;
return FullMath.mulDiv(valueNow, ONE, valueHold);
}
}
src/libraries/Price.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.38;
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {IReferencePrice} from "../interfaces/IReferencePrice.sol";
/// @title Price
/// @notice Reads a pool's price source and decides "live" or "no price". It never reverts:
/// a source that reverts, lies about the shape of its answer or burns gas simply has no price.
library Price {
/// @notice The gas a price source may use. A source that needs more has no price.
uint256 internal constant READ_GAS = 150_000;
/// @notice The oldest a price may ever be allowed to be: 3 days.
uint256 internal constant MAX_PRICE_AGE = 259_200;
/// @notice Asks `source` for the price of the pair.
/// @return live false for: a revert, an answer that is not exactly two words, a price of zero or outside
/// v4's price range, a price from the future, a price older than `maxAge`.
/// @return sqrtPriceX96 the price when live, else 0
function read(address source, Currency currency0, Currency currency1, uint256 maxAge)
internal
view
returns (bool live, uint160 sqrtPriceX96)
{
bytes memory ask = abi.encodeCall(IReferencePrice.price, (currency0, currency1));
bool ok;
uint256 size;
uint256 answer;
uint256 updatedAt;
uint256 gasCap = READ_GAS;
assembly ("memory-safe") {
// the answer is copied into two words of scratch space only: a huge answer cannot cost memory
ok := staticcall(gasCap, source, add(ask, 0x20), mload(ask), 0x00, 0x40)
size := returndatasize()
answer := mload(0x00)
updatedAt := mload(0x20)
}
if (!ok || size != 64) return (false, 0);
if (answer < TickMath.MIN_SQRT_PRICE || answer >= TickMath.MAX_SQRT_PRICE) return (false, 0);
if (updatedAt > block.timestamp || block.timestamp - updatedAt > maxAge) return (false, 0);
return (true, uint160(answer));
}
}
src/libraries/Receipts.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.38;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "@uniswap/v4-core/src/types/PoolId.sol";
import {BalanceDelta, toBalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {IMandate} from "../interfaces/IMandate.sol";
import {Store} from "./Store.sol";
/// @notice What a pool's credential registry answers: does `payee` hold the registry's one credential.
interface IPayeeRegistry {
function holds(address payee) external view returns (bool);
}
/// @notice What a pool's named router answers: who sent the swap to it.
interface IMsgSender {
function msgSender() external view returns (address);
}
/// @title Receipts
/// @notice A swap whose hookData is abi.encode(bytes32 payee, bytes32 orderRef) leaves one receipt. Nothing here can
/// refuse a swap, move money, return a delta or change a price: bad data only means no receipt.
library Receipts {
using PoolIdLibrary for PoolKey;
uint8 internal constant OFF = 0;
uint8 internal constant ANY = 1;
uint8 internal constant CREDENTIAL = 2;
uint8 internal constant WINDOW = 3;
uint8 internal constant MALFORMED = 1;
uint8 internal constant NOT_ALLOWED = 2;
uint8 internal constant REPEATED = 3;
/// @notice The gas a registry or a router may use for its one answer.
uint256 internal constant READ_GAS = 30_000;
/// @notice OPEN's check: each rule carries exactly the fields it uses.
function check(Store.Settings calldata s) internal view {
uint8 r = s.receipts;
bool ok = r <= WINDOW && (r == CREDENTIAL) == (s.payeeRegistry != address(0))
&& (r == WINDOW ? s.windowStart < s.windowEnd : (s.windowStart | s.windowEnd) == 0)
&& (r != OFF || s.router == address(0));
if (ok && r == CREDENTIAL) ok = s.payeeRegistry.code.length != 0;
if (ok && s.router != address(0)) ok = s.router.code.length != 0;
if (!ok) revert IMandate.BadReceipts();
}
/// @notice After a swap: write the receipt the hookData asks for, or say why not. `swapped` is the swapper's whole delta.
function write(PoolKey calldata key, address sender, BalanceDelta swapped, bytes calldata hookData) internal {
if (hookData.length == 0) return;
PoolId id = key.toId();
Store.Settings storage set = Store.store().settings[id];
if (set.receipts == OFF) return;
if (hookData.length != 64) return _refuse(id, sender, MALFORMED);
(bytes32 rawPayee, bytes32 orderRef) = abi.decode(hookData, (bytes32, bytes32));
if (uint256(rawPayee) >> 160 != 0) return _refuse(id, sender, MALFORMED);
address payee = address(uint160(uint256(rawPayee)));
if (!_allowed(set, payee)) return _refuse(id, sender, NOT_ALLOWED);
_record(id, payee, orderRef, sender == set.router ? set.router : address(0), sender, swapped);
}
/// @dev `router` is the pool's router when it sent this swap (zero otherwise): it is asked who the payer is.
function _record(PoolId id, address payee, bytes32 orderRef, address router, address sender, BalanceDelta swapped)
private
{
address payer = router == address(0) ? address(0) : _read(router, abi.encodeCall(IMsgSender.msgSender, ()));
bytes32 receiptId = keccak256(abi.encode(id, payee, orderRef, payer));
Store.Layout storage st = Store.store();
if (st.receipts[receiptId]) return _refuse(id, sender, REPEATED);
st.receipts[receiptId] = true;
emit IMandate.Receipt(receiptId, id, payee, orderRef, payer, sender, swapped.amount0(), swapped.amount1());
}
function _allowed(Store.Settings storage set, address payee) private view returns (bool) {
uint8 r = set.receipts;
if (r == ANY) return true;
if (r == WINDOW) return block.timestamp >= set.windowStart && block.timestamp < set.windowEnd;
// CREDENTIAL: a yes is exactly the 32-byte word 1; anything else, a revert or too much gas is a no
return _read(set.payeeRegistry, abi.encodeCall(IPayeeRegistry.holds, (payee))) == address(1);
}
/// @dev One capped staticcall whose answer must be exactly one 32-byte word; it is returned as an address-sized
/// value, and zero when the call failed, ran out of gas or answered anything else. Never copies more than 32 bytes.
function _read(address target, bytes memory data) private view returns (address out) {
uint256 gasCap = READ_GAS;
assembly ("memory-safe") {
let ok := staticcall(gasCap, target, add(data, 0x20), mload(data), 0, 0)
if and(ok, eq(returndatasize(), 0x20)) {
returndatacopy(0, 0, 0x20)
let word := mload(0)
if iszero(shr(160, word)) { out := word }
}
}
}
function _refuse(PoolId id, address sender, uint8 reason) private {
emit IMandate.ReceiptRefused(id, sender, reason);
}
}
src/libraries/Store.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.38;
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
import {FeeBook} from "./FeeBook.sol";
/// @title Store
/// @notice The hook's one storage slot. The hook and every library reach the same layout through
/// `store()`, so a library that runs by DELEGATECALL reads and writes the hook's own state.
library Store {
/// @notice A pool's settings: chosen once, when it opens, and never changed.
/// @param curator the only account that may open the pool and steer its range
/// @param feeCapBps the curator's fee, as basis points of the gain above the high-water mark (at most 2,000)
/// @param vestPeriod the seconds over which a curator fee is released
/// @param maxAge the oldest a Chainlink price may be, in seconds, and still count as live
/// @param source the price source that answers for this pair (on the hook's approved list)
/// @param widthMin the narrowest the range may be, in ticks
/// @param widthMax the widest the range may be, in ticks
/// @param offsetMax how far the range's centre may be from Chainlink's tick
/// @param capacity the most shares the pool may ever have
/// @param feeBase the swap fee when calm and on Chainlink's price, in pips (changing-fee pools only)
/// @param feeCap the most a swap can ever pay, in pips, at most 10,000 (1%); zero means the pool has a fixed fee
/// @param gapSlope pips added per tick between the pool's price and Chainlink's
/// @param moveSlope pips added per tick Chainlink's price moved since the hook last looked
/// @param flow which swaps pay the gap term: 0 every swap, 1 only a swap that moves the pool away from
/// Chainlink's price, 2 only a swap that moves it back toward it (changing-fee pools only)
/// @param receipts 0 off, 1 a receipt for any payee, 2 only for a payee that holds `payeeRegistry`'s credential,
/// 3 only inside [windowStart, windowEnd)
/// @param payeeRegistry the credential registry of rule 2 (zero otherwise)
/// @param windowStart the first second of rule 3's window (zero otherwise)
/// @param windowEnd the first second after rule 3's window (zero otherwise)
/// @param router the router whose msgSender() is a receipt's payer; zero means receipts carry no payer
/// @param shareBps the slice of every swap fee the range collects that goes to the pool's named recipients, in basis
/// points (0 off, at most 3,000); the rest stays with the providers
/// @param standing 1 lets a provider's signed standing order (EXIT_BELOW / EXIT_ABOVE) be run by anyone; 0 off
struct Settings {
address curator;
uint16 feeCapBps;
uint32 vestPeriod;
uint32 maxAge;
address source;
int24 widthMin;
int24 widthMax;
int24 offsetMax;
uint128 capacity;
uint24 feeBase;
uint24 feeCap;
uint24 gapSlope;
uint24 moveSlope;
uint8 flow;
uint8 receipts;
address payeeRegistry;
uint40 windowStart;
uint40 windowEnd;
address router;
uint8 standing;
uint16 shareBps;
address registry;
address plugin;
uint8 gate;
bytes32 gateRoot;
address gateVerifier;
}
/// @notice A pool's book: the numbers that change.
/// @param lower the range's lower tick
/// @param upper the range's upper tick
/// @param lookedBlock the last block whose first swap asked the rule whether to move the range
/// @param movedBlock the last block in which the range moved (at most one move per block)
/// @param nonce the curator's signing number: a signed range names it, and it is used once
/// @param lastRefTick Chainlink's tick when the hook last looked (for the fee's move term)
/// @param moveTicks how far Chainlink's price has moved in the current block: every swap of that block pays it
/// @param idle0 token0 that does not fit the range, held as claims on the PoolManager
/// @param idle1 the same for token1
/// @param hold0 the hold basket: the token0 the providers would hold had nothing been done
/// @param hold1 the same for token1
/// @dev idle0/idle1 share one slot and hold0/hold1 another (every join, exit and re-centre writes both of a pair):
/// 3 slots after the packed first one instead of 4. A write at or above 2^128 reverts (SafeCast), as v4's own
/// amounts are 128-bit.
/// @param marks the curator-fee marks (FeeBook)
struct Book {
int24 lower;
int24 upper;
uint48 lookedBlock;
uint48 movedBlock;
uint64 nonce;
int24 lastRefTick;
uint24 moveTicks;
uint128 idle0;
uint128 idle1;
uint128 hold0;
uint128 hold1;
FeeBook.Marks marks;
}
/// @notice Limit orders of one pool, tick, direction and epoch (Orders).
/// @param filled true once a swap crossed the bucket and afterSwap took it out
/// @param liquidity the liquidity of all orders in the bucket
/// @param amount0 what the bucket turned into, set when it is filled
/// @param sizes each owner's liquidity in the bucket
struct Bucket {
bool filled;
uint128 liquidity;
uint256 amount0;
uint256 amount1;
mapping(address owner => uint128) sizes;
// audit A2: the swap fees the bucket's shared position earned, per unit of liquidity (x 2^128, rounded down),
// and each owner's reading of it from when it last placed
uint256 growth0;
uint256 growth1;
mapping(address owner => uint256) kept0;
mapping(address owner => uint256) kept1;
}
/// @notice A waiting swap (Waits).
/// @param left the parked token still waiting
/// @param got the other token the fills gave
/// @param limit the worst Chainlink price the owner accepts, as sqrtPriceX96 (0: none): a wait selling token0 is
/// filled only at or above it, one selling token1 only at or below it
/// @param expiry the last second the wait may be filled (0: none); what is left is the owner's to take back
/// @dev Ordered for packing: owner and zeroForOne share a slot, left and got share one (a fill writes both). The
/// limit and the expiry were appended (2026-11-20) and share a fourth slot: the first three never moved.
struct Wait {
address owner;
bool zeroForOne;
PoolId pool;
uint128 left;
uint128 got;
uint160 limit;
uint40 expiry;
}
/// @notice The people who share a pool's released curator fee besides the curator (FeeSplit).
/// @param to the recipients, at most eight
/// @param bps each one's share of the released fee, in basis points; the curator keeps the rest
struct Split {
address[] to;
uint16[] bps;
}
/// @notice The lists a pool may name at OPEN, beside its settings: the curator-fee split and the swap-fee
/// share. Either may be empty.
struct Lists {
address[] splitTo;
uint16[] splitBps;
address[] shareTo;
uint16[] shareBps;
}
/// @notice What the hook owes one recipient of a pool's swap-fee share, in each currency.
struct Owed {
uint256 amount0;
uint256 amount1;
}
struct Layout {
mapping(PoolId => Settings) settings;
mapping(PoolId => Book) book;
// ---- the share ledger ----
mapping(uint256 id => uint256) totalSupply;
mapping(address owner => mapping(uint256 id => uint256)) balanceOf;
mapping(address owner => mapping(address spender => mapping(uint256 id => uint256))) allowance;
mapping(address owner => mapping(address operator => bool)) isOperator;
// ---- limit orders (appended: the layout above never moves) ----
mapping(bytes32 slot => uint256) orderEpoch;
mapping(bytes32 bucket => Bucket) buckets;
// ---- waiting swaps (appended) ----
uint256 waitCount;
mapping(uint256 number => Wait) waits;
mapping(bytes32 queue => mapping(uint256 => uint256)) waitQueue;
mapping(bytes32 queue => uint256) waitHead;
mapping(bytes32 queue => uint256) waitTail;
// ---- the fee split (appended) ----
mapping(PoolId => Split) splits;
// the receipts already written, by id = keccak256(pool, payee, orderRef, payer)
mapping(bytes32 receiptId => bool) receipts;
// each owner's order epoch (cancel or a transfer out raises it) and the orders already run
mapping(address owner => uint64) standingEpoch;
mapping(bytes32 orderHash => bool) standingUsed;
// each pool's swap-fee share list (its bps divide the slice) and what each recipient is owed
mapping(PoolId => Split) shares;
mapping(PoolId => mapping(address recipient => Owed)) owed;
// the accounts a LIST gate has admitted, per pool
mapping(PoolId => mapping(address account => bool)) admitted;
}
/// @dev keccak256(abi.encode(uint256(keccak256("mandate.store")) - 1)) & ~bytes32(uint256(0xff)) (ERC-7201)
bytes32 internal constant SLOT = 0x3acd032230c714e0bd8b91b2215121d0e171997db5f2bfe7840bbd50b08f1c00;
function store() internal pure returns (Layout storage s) {
bytes32 slot = SLOT;
assembly ("memory-safe") {
s.slot := slot
}
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {
"src/libraries/Money.sol": {
"Money": "0x2D60dbfB22835f61099A98Bef673221D546d5Ce1"
},
"src/libraries/Waits.sol": {
"Waits": "0xC87eb1951a2902f7c4ffA8C6DA9FF89998116477"
},
"src/libraries/Orders.sol": {
"Orders": "0x841e240463238662534DA0C280873fF3610f9a33"
},
"src/libraries/Opening.sol": {
"Opening": "0xe0a7ca57c90D541d35E6AcC0Da68e1E9602A35C8"
},
"src/libraries/Curation.sol": {
"Curation": "0x2D1d0C39Cbb0cCCb08E66E869a84Be1338424F27"
},
"src/libraries/Swapping.sol": {
"Swapping": "0xE780F756834F4c167245885F0dbF9134f99C8E9D"
}
},
"optimizer": {
"runs": 1000000,
"enabled": true
},
"viaSSACFG": false,
"evmVersion": "cancun",
"remappings": [
"forge-std/=lib/forge-std/src/",
"hookmate/=lib/hookmate/src/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@uniswap/v4-core/=lib/uniswap-hooks/lib/v4-core/",
"@uniswap/v4-periphery/=lib/uniswap-hooks/lib/v4-periphery/",
"solmate/=lib/uniswap-hooks/lib/v4-core/lib/solmate/",
"@chainlink/contracts-ccip/contracts/=lib/chainlink-ccip/chains/evm/contracts/",
"@chainlink/contracts/=lib/chainlink-evm/contracts/",
"@openzeppelin/[email protected]/=lib/openzeppelin-contracts/contracts/",
"@openzeppelin/[email protected]/=lib/openzeppelin-contracts/contracts/",
"lib/uniswap-hooks/lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/:ds-test/=lib/uniswap-hooks/lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/lib/ds-test/src/",
"lib/uniswap-hooks/lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/:ds-test/=lib/uniswap-hooks/lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/lib/ds-test/src/",
"lib/uniswap-hooks/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/uniswap-hooks/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/uniswap-hooks/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/uniswap-hooks/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/uniswap-hooks/lib/v4-periphery/lib/permit2/lib/forge-std/:ds-test/=lib/uniswap-hooks/lib/v4-periphery/lib/permit2/lib/forge-std/lib/ds-test/src/",
"lib/uniswap-hooks/lib/v4-periphery/lib/permit2/lib/forge-std/:ds-test/=lib/uniswap-hooks/lib/v4-periphery/lib/permit2/lib/forge-std/lib/ds-test/src/",
"lib/uniswap-hooks/lib/v4-periphery/lib/permit2/lib/solmate/:ds-test/=lib/uniswap-hooks/lib/v4-periphery/lib/permit2/lib/solmate/lib/ds-test/src/",
"lib/uniswap-hooks/lib/v4-periphery/lib/permit2/lib/solmate/:ds-test/=lib/uniswap-hooks/lib/v4-periphery/lib/permit2/lib/solmate/lib/ds-test/src/",
"lib/uniswap-hooks/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/uniswap-hooks/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/uniswap-hooks/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/uniswap-hooks/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/uniswap-hooks/lib/v4-periphery/lib/v4-core/lib/solmate/:ds-test/=lib/uniswap-hooks/lib/v4-periphery/lib/v4-core/lib/solmate/lib/ds-test/src/",
"lib/uniswap-hooks/lib/v4-periphery/lib/v4-core/lib/solmate/:ds-test/=lib/uniswap-hooks/lib/v4-periphery/lib/v4-core/lib/solmate/lib/ds-test/src/",
"lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/uniswap-hooks/lib/v4-core/lib/solmate/:ds-test/=lib/uniswap-hooks/lib/v4-core/lib/solmate/lib/ds-test/src/",
"lib/uniswap-hooks/lib/v4-core/lib/solmate/:ds-test/=lib/uniswap-hooks/lib/v4-core/lib/solmate/lib/ds-test/src/",
"lib/uniswap-hooks/lib/v4-periphery/lib/permit2/:openzeppelin-contracts/=lib/uniswap-hooks/lib/v4-periphery/lib/permit2/lib/openzeppelin-contracts/",
"lib/uniswap-hooks/lib/v4-periphery/lib/permit2/:openzeppelin-contracts/=lib/uniswap-hooks/lib/v4-periphery/lib/permit2/lib/openzeppelin-contracts/",
"lib/uniswap-hooks/lib/v4-periphery/lib/v4-core/:openzeppelin-contracts/=lib/uniswap-hooks/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"lib/uniswap-hooks/lib/v4-periphery/lib/v4-core/:openzeppelin-contracts/=lib/uniswap-hooks/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"lib/uniswap-hooks/lib/v4-core/:openzeppelin-contracts/=lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/",
"lib/uniswap-hooks/lib/v4-core/:openzeppelin-contracts/=lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/",
"lib/uniswap-hooks/lib/v4-periphery/:v4-core/=lib/uniswap-hooks/lib/v4-periphery/lib/v4-core/src/",
"lib/uniswap-hooks/lib/v4-periphery/:v4-core/=lib/uniswap-hooks/lib/v4-periphery/lib/v4-core/src/",
"lib/uniswap-hooks/:v4-core/=lib/uniswap-hooks/lib/v4-core/src/",
"lib/uniswap-hooks/:v4-core/=lib/uniswap-hooks/lib/v4-core/src/",
"@ensdomains/=lib/uniswap-hooks/lib/v4-core/node_modules/@ensdomains/",
"@openzeppelin/=lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/",
"chainlink-ccip/=lib/chainlink-ccip/",
"chainlink-evm/=lib/chainlink-evm/contracts/",
"ds-test/=lib/uniswap-hooks/lib/v4-core/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=lib/uniswap-hooks/lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
"hardhat/=lib/uniswap-hooks/lib/v4-core/node_modules/hardhat/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"permit2/=lib/uniswap-hooks/lib/v4-periphery/lib/permit2/",
"uniswap-hooks/=lib/uniswap-hooks/src/",
"v4-core/=lib/uniswap-hooks/lib/v4-core/src/",
"v4-periphery/=lib/uniswap-hooks/lib/v4-periphery/"
],
"experimental": false
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.