Source Code
Overview
ETH Balance
4.423030412673048279 ETH
Token Holdings
More Info
ContractCreator
Multichain Info
N/A
Latest 25 from a total of 196 transactions
Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
---|---|---|---|---|---|---|---|---|---|
Initialize | 2163003 | 210 days ago | IN | 0 ETH | 0.00000679 | ||||
Initialize | 2162990 | 210 days ago | IN | 0 ETH | 0.00000708 | ||||
Initialize | 2162927 | 210 days ago | IN | 0 ETH | 0.00000693 | ||||
Initialize | 2162897 | 210 days ago | IN | 0 ETH | 0.00000715 | ||||
Initialize | 2162159 | 210 days ago | IN | 0 ETH | 0.00001342 | ||||
Initialize | 2162020 | 210 days ago | IN | 0 ETH | 0.00001744 | ||||
Initialize | 2161937 | 210 days ago | IN | 0 ETH | 0.0000197 | ||||
Initialize | 2161325 | 210 days ago | IN | 0 ETH | 0.00002982 | ||||
Initialize | 2161292 | 210 days ago | IN | 0 ETH | 0.00002732 | ||||
Initialize | 2143908 | 213 days ago | IN | 0 ETH | 0.00000168 | ||||
Initialize | 2143854 | 213 days ago | IN | 0 ETH | 0.00000172 | ||||
Initialize | 2143831 | 213 days ago | IN | 0 ETH | 0.00000179 | ||||
Initialize | 2143789 | 213 days ago | IN | 0 ETH | 0.000002 | ||||
Initialize | 2143777 | 213 days ago | IN | 0 ETH | 0.00000208 | ||||
Initialize | 2143771 | 213 days ago | IN | 0 ETH | 0.00000209 | ||||
Initialize | 2143698 | 213 days ago | IN | 0 ETH | 0.00000027 | ||||
Initialize | 2143693 | 213 days ago | IN | 0 ETH | 0.00000027 | ||||
Initialize | 2143520 | 213 days ago | IN | 0 ETH | 0.00000023 | ||||
Initialize | 2143492 | 213 days ago | IN | 0 ETH | 0.00000019 | ||||
Initialize | 2143483 | 213 days ago | IN | 0 ETH | 0.0000002 | ||||
Initialize | 2143475 | 213 days ago | IN | 0 ETH | 0.0000002 | ||||
Initialize | 2143447 | 213 days ago | IN | 0 ETH | 0.00001047 | ||||
Initialize | 2143441 | 213 days ago | IN | 0 ETH | 0.00002067 | ||||
Initialize | 2143435 | 213 days ago | IN | 0 ETH | 0.00002131 | ||||
Initialize | 2143428 | 213 days ago | IN | 0 ETH | 0.00000001 |
Latest 25 internal transactions (View All)
Advanced mode:
Parent Transaction Hash | Method | Block |
From
|
To
|
|||
---|---|---|---|---|---|---|---|
Transfer | 2161461 | 210 days ago | 0.00065104 ETH | ||||
Transfer | 2161461 | 210 days ago | 0.03190117 ETH | ||||
Settle | 2161405 | 210 days ago | 0.5 ETH | ||||
Transfer | 2161405 | 210 days ago | 0.00455531 ETH | ||||
Settle | 2161373 | 210 days ago | 0.5 ETH | ||||
Settle | 2161334 | 210 days ago | 1 ETH | ||||
Settle | 2154377 | 211 days ago | 0.01 ETH | ||||
Settle | 2154373 | 211 days ago | 0.001 ETH | ||||
Transfer | 2154373 | 211 days ago | 0.00099999 ETH | ||||
Settle | 2150766 | 212 days ago | 0.001 ETH | ||||
Transfer | 2143842 | 213 days ago | 0.00000914 ETH | ||||
Transfer | 2143842 | 213 days ago | 0.00044826 ETH | ||||
Settle | 2143840 | 213 days ago | 0.0008 ETH | ||||
Settle | 2143838 | 213 days ago | 0.0005 ETH | ||||
Transfer | 2143810 | 213 days ago | 0.00004574 ETH | ||||
Transfer | 2143810 | 213 days ago | 0.00224152 ETH | ||||
Settle | 2143808 | 213 days ago | 0.005 ETH | ||||
Settle | 2143806 | 213 days ago | 0.001 ETH | ||||
Transfer | 2143798 | 213 days ago | 0.00000091 ETH | ||||
Transfer | 2143798 | 213 days ago | 0.00004478 ETH | ||||
Settle | 2143796 | 213 days ago | 0.0005 ETH | ||||
Settle | 2143794 | 213 days ago | 0.0001 ETH | ||||
Settle | 2143530 | 213 days ago | 0.001 ETH | ||||
Transfer | 2143399 | 213 days ago | 0.07196161 ETH | ||||
Transfer | 2143399 | 213 days ago | 0.0014686 ETH |
Loading...
Loading
Contract Source Code Verified (Exact Match)
Contract Name:
Manager
Compiler Version
v0.8.24+commit.e11b9ed9
Optimization Enabled:
Yes with 1000 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.24; import {PoolManager} from "../lib/v4-core/src/PoolManager.sol"; contract Manager is PoolManager { constructor(uint256 controllerGasLimit) PoolManager(controllerGasLimit) {} }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; /** * @dev Standard ERC20 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens. */ interface IERC20Errors { /** * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. * @param balance Current balance for the interacting account. * @param needed Minimum amount required to perform a transfer. */ error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC20InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC20InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers. * @param spender Address that may be allowed to operate on tokens without being their owner. * @param allowance Amount of tokens a `spender` is allowed to operate with. * @param needed Minimum amount required to perform a transfer. */ error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC20InvalidApprover(address approver); /** * @dev Indicates a failure with the `spender` to be approved. Used in approvals. * @param spender Address that may be allowed to operate on tokens without being their owner. */ error ERC20InvalidSpender(address spender); } /** * @dev Standard ERC721 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens. */ interface IERC721Errors { /** * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20. * Used in balance queries. * @param owner Address of the current owner of a token. */ error ERC721InvalidOwner(address owner); /** * @dev Indicates a `tokenId` whose `owner` is the zero address. * @param tokenId Identifier number of a token. */ error ERC721NonexistentToken(uint256 tokenId); /** * @dev Indicates an error related to the ownership over a particular token. Used in transfers. * @param sender Address whose tokens are being transferred. * @param tokenId Identifier number of a token. * @param owner Address of the current owner of a token. */ error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC721InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC721InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `operator`’s approval. Used in transfers. * @param operator Address that may be allowed to operate on tokens without being their owner. * @param tokenId Identifier number of a token. */ error ERC721InsufficientApproval(address operator, uint256 tokenId); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC721InvalidApprover(address approver); /** * @dev Indicates a failure with the `operator` to be approved. Used in approvals. * @param operator Address that may be allowed to operate on tokens without being their owner. */ error ERC721InvalidOperator(address operator); } /** * @dev Standard ERC1155 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens. */ interface IERC1155Errors { /** * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. * @param balance Current balance for the interacting account. * @param needed Minimum amount required to perform a transfer. * @param tokenId Identifier number of a token. */ error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC1155InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC1155InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `operator`’s approval. Used in transfers. * @param operator Address that may be allowed to operate on tokens without being their owner. * @param owner Address of the current owner of a token. */ error ERC1155MissingApprovalForAll(address operator, address owner); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC1155InvalidApprover(address approver); /** * @dev Indicates a failure with the `operator` to be approved. Used in approvals. * @param operator Address that may be allowed to operate on tokens without being their owner. */ error ERC1155InvalidOperator(address operator); /** * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation. * Used in batch transfers. * @param idsLength Length of the array of token identifiers * @param valuesLength Length of the array of token amounts */ error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.20; import {IERC20} from "./IERC20.sol"; import {IERC20Metadata} from "./extensions/IERC20Metadata.sol"; import {Context} from "../../utils/Context.sol"; import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * * TIP: For a detailed writeup see our guide * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * The default value of {decimals} is 18. To change this, you should override * this function so it returns a different value. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Indicates a failed `decreaseAllowance` request. */ error ERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease); /** * @dev Sets the values for {name} and {symbol}. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the default value returned by this function, unless * it's overridden. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `value`. */ function transfer(address to, uint256 value) public virtual returns (bool) { address owner = _msgSender(); _transfer(owner, to, value); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `value`. * - the caller must have allowance for ``from``'s tokens of at least * `value`. */ function transferFrom(address from, address to, uint256 value) public virtual returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, value); _transfer(from, to, value); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `requestedDecrease`. * * NOTE: Although this function is designed to avoid double spending with {approval}, * it can still be frontrunned, preventing any attempt of allowance reduction. */ function decreaseAllowance(address spender, uint256 requestedDecrease) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); if (currentAllowance < requestedDecrease) { revert ERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease); } unchecked { _approve(owner, spender, currentAllowance - requestedDecrease); } return true; } /** * @dev Moves a `value` amount of tokens from `from` to `to`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * NOTE: This function is not virtual, {_update} should be overridden instead. */ function _transfer(address from, address to, uint256 value) internal { if (from == address(0)) { revert ERC20InvalidSender(address(0)); } if (to == address(0)) { revert ERC20InvalidReceiver(address(0)); } _update(from, to, value); } /** * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from` (or `to`) is * the zero address. All customizations to transfers, mints, and burns should be done by overriding this function. * * Emits a {Transfer} event. */ function _update(address from, address to, uint256 value) internal virtual { if (from == address(0)) { // Overflow check required: The rest of the code assumes that totalSupply never overflows _totalSupply += value; } else { uint256 fromBalance = _balances[from]; if (fromBalance < value) { revert ERC20InsufficientBalance(from, fromBalance, value); } unchecked { // Overflow not possible: value <= fromBalance <= totalSupply. _balances[from] = fromBalance - value; } } if (to == address(0)) { unchecked { // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply. _totalSupply -= value; } } else { unchecked { // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256. _balances[to] += value; } } emit Transfer(from, to, value); } /** * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0). * Relies on the `_update` mechanism * * Emits a {Transfer} event with `from` set to the zero address. * * NOTE: This function is not virtual, {_update} should be overridden instead. */ function _mint(address account, uint256 value) internal { if (account == address(0)) { revert ERC20InvalidReceiver(address(0)); } _update(address(0), account, value); } /** * @dev Destroys a `value` amount of tokens from `account`, by transferring it to address(0). * Relies on the `_update` mechanism. * * Emits a {Transfer} event with `to` set to the zero address. * * NOTE: This function is not virtual, {_update} should be overridden instead */ function _burn(address account, uint256 value) internal { if (account == address(0)) { revert ERC20InvalidSender(address(0)); } _update(account, address(0), value); } /** * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal virtual { _approve(owner, spender, value, true); } /** * @dev Alternative version of {_approve} with an optional flag that can enable or disable the Approval event. * * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any * `Approval` event during `transferFrom` operations. * * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to true * using the following override: * ``` * function _approve(address owner, address spender, uint256 value, bool) internal virtual override { * super._approve(owner, spender, value, true); * } * ``` * * Requirements are the same as {_approve}. */ function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual { if (owner == address(0)) { revert ERC20InvalidApprover(address(0)); } if (spender == address(0)) { revert ERC20InvalidSpender(address(0)); } _allowances[owner][spender] = value; if (emitEvent) { emit Approval(owner, spender, value); } } /** * @dev Updates `owner` s allowance for `spender` based on spent `value`. * * Does not update the allowance value in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance(address owner, address spender, uint256 value) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { if (currentAllowance < value) { revert ERC20InsufficientAllowance(spender, currentAllowance, value); } unchecked { _approve(owner, spender, currentAllowance - value, false); } } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.20; import {IERC20} from "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the value of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the value of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves a `value` amount of tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 value) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets a `value` amount of tokens as the allowance of `spender` over the * caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 value) external returns (bool); /** * @dev Moves a `value` amount of tokens from `from` to `to` using the * allowance mechanism. `value` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 value) external returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.20; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; interface IUnlockCallback { /// @notice Called by the pool manager on `msg.sender` when the manager is unlocked /// @param data The data that was passed to the call to unlock /// @return Any data that you want to be returned from the unlock call function unlockCallback(bytes calldata data) external returns (bytes memory); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @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 the balance of a token /// @param account The account for which to look up the number of tokens it has, i.e. its balance /// @return The number of tokens held by the account function balanceOf(address account) external view returns (uint256); /// @notice Transfers the amount of token from the `msg.sender` to the recipient /// @param recipient The account that will receive the amount transferred /// @param amount The number of tokens to send from the sender to the recipient /// @return Returns true for a successful transfer, false for an unsuccessful transfer function transfer(address recipient, uint256 amount) external returns (bool); /// @notice Returns the current allowance given to a spender by an owner /// @param owner The account of the token owner /// @param spender The account of the token spender /// @return The current allowance granted by `owner` to `spender` function allowance(address owner, address spender) external view returns (uint256); /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount` /// @param spender The account which will be allowed to spend a given amount of the owners tokens /// @param amount The amount of tokens allowed to be used by `spender` /// @return Returns true for a successful approval, false for unsuccessful function approve(address spender, uint256 amount) external returns (bool); /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender` /// @param sender The account from which the transfer will be initiated /// @param recipient The recipient of the transfer /// @param amount The amount of the transfer /// @return Returns true for a successful transfer, false for unsuccessful function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`. /// @param from The account from which the tokens were sent, i.e. the balance decreased /// @param to The account to which the tokens were sent, i.e. the balance increased /// @param value The amount of tokens that were transferred event Transfer(address indexed from, address indexed to, uint256 value); /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes. /// @param owner The account that approved spending of its tokens /// @param spender The account for which the spending allowance was modified /// @param value The new allowance from the owner to the spender event Approval(address indexed owner, address indexed spender, uint256 value); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface IERC6909Claims { /// @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. 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. 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. function approve(address spender, uint256 id, uint256 amount) external returns (bool); /// @notice Sets or removes a spender as an operator for the caller. /// @param spender The address of the spender. /// @param approved The approval status. function setOperator(address spender, bool approved) external returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; 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 slot Key of slot to start sloading from /// @param nSlots Number of slots to load into return value /// @return value The value of the sload-ed slots concatenated as dynamic bytes function extsload(bytes32 slot, uint256 nSlots) external view returns (bytes memory value); /// @notice Called by external contracts to access sparse pool state /// @param slots List of slots to SLOAD from. /// @return values List of loaded values. function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.24; interface IExttload { /// @notice Called by external contracts to access transient storage of the contract /// @param slot Key of slot to tload /// @return value The value of the slot as bytes32 function exttload(bytes32 slot) external view returns (bytes32 value); /// @notice Called by external contracts to access sparse transient pool state /// @param slots List of slots to tload /// @return values List of loaded values function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {PoolKey} from "../types/PoolKey.sol"; import {BalanceDelta} from "../types/BalanceDelta.sol"; import {IPoolManager} from "./IPoolManager.sol"; import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol"; /// @notice The PoolManager contract decides whether to invoke specific hooks by inspecting the leading bits /// of the hooks contract address. For example, a 1 bit in the first bit of the address will /// cause the 'before swap' hook to be invoked. 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 /// @param hookData Arbitrary data handed into the PoolManager by the initializer to be be passed on to the hook /// @return bytes4 The function selector for the hook function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, bytes calldata hookData) 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 /// @param hookData Arbitrary data handed into the PoolManager by the initializer to be be passed on to the hook /// @return bytes4 The function selector for the hook function afterInitialize( address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick, bytes calldata hookData ) 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, IPoolManager.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 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, IPoolManager.ModifyLiquidityParams calldata params, BalanceDelta delta, 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 liquidty provider to be be passed on to the hook /// @return bytes4 The function selector for the hook function beforeRemoveLiquidity( address sender, PoolKey calldata key, IPoolManager.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 hookData Arbitrary data handed into the PoolManager by the liquidty 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, IPoolManager.ModifyLiquidityParams calldata params, BalanceDelta delta, 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 leading bit is set to 1 (24th bit, 0x800000), 3) the value is less than or equal to the maximum fee (1 million) function beforeSwap( address sender, PoolKey calldata key, IPoolManager.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, IPoolManager.SwapParams calldata params, BalanceDelta delta, bytes calldata hookData ) external returns (bytes4, int128); /// @notice The hook called before donate /// @param sender The initial msg.sender for the donate call /// @param key The key for the pool /// @param amount0 The amount of token0 being donated /// @param amount1 The amount of token1 being donated /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook /// @return bytes4 The function selector for the hook function beforeDonate( address sender, PoolKey calldata key, uint256 amount0, uint256 amount1, bytes calldata hookData ) external returns (bytes4); /// @notice The hook called after donate /// @param sender The initial msg.sender for the donate call /// @param key The key for the pool /// @param amount0 The amount of token0 being donated /// @param amount1 The amount of token1 being donated /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook /// @return bytes4 The function selector for the hook function afterDonate( address sender, PoolKey calldata key, uint256 amount0, uint256 amount1, bytes calldata hookData ) external returns (bytes4); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {Currency} from "../types/Currency.sol"; import {PoolKey} from "../types/PoolKey.sol"; import {Pool} from "../libraries/Pool.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 {Position} from "../libraries/Position.sol"; import {IExtsload} from "./IExtsload.sol"; import {IExttload} from "./IExttload.sol"; 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(); /// @notice Pools must have a positive non-zero tickSpacing passed to #initialize error TickSpacingTooSmall(); /// @notice PoolKey must have currencies where address(currency0) < address(currency1) error CurrenciesOutOfOrderOrEqual(); /// @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 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 event Initialize( PoolId id, Currency indexed currency0, Currency indexed currency1, uint24 fee, int24 tickSpacing, IHooks hooks ); /// @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 event ModifyLiquidity( PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta ); /// @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 sender, int128 amount0, int128 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick, uint24 fee ); /// @notice Returns the constant representing the maximum tickSpacing for an initialized pool key function MAX_TICK_SPACING() external view returns (int24); /// @notice Returns the constant representing the minimum tickSpacing for an initialized pool key function MIN_TICK_SPACING() external view returns (int24); /// @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. function sync(Currency currency) external returns (uint256 balance); /// @notice Initialize the state for a given pool ID function initialize(PoolKey memory key, uint160 sqrtPriceX96, bytes calldata hookData) external returns (int24 tick); /// @notice All operations go through this function /// @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); 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 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 Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)` /// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal and fee deltas. /// @return feeDelta The balance delta of the fees generated in the liquidity range. Returned for informational purposes. function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData) external returns (BalanceDelta, BalanceDelta); struct SwapParams { bool zeroForOne; int256 amountSpecified; uint160 sqrtPriceLimitX96; } /// @notice Swap against the given pool /// @param key The pool to swap in /// @param params The parameters for swapping /// @param hookData Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)` /// @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); /// @notice Donate the given currency amounts to the pool with the given pool key function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData) external returns (BalanceDelta); /// @notice Called by the user to net out some value owed to the user /// @dev Can also be used as a mechanism for _free_ flash loans function take(Currency currency, address to, uint256 amount) external; /// @notice Called by the user to move value into ERC6909 balance function mint(address to, uint256 id, uint256 amount) external; /// @notice Called by the user to move value from ERC6909 balance function burn(address from, uint256 id, uint256 amount) external; /// @notice Called by the user to pay what is owed function settle(Currency token) external payable returns (uint256 paid); /// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees. function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import {PoolKey} from "../types/PoolKey.sol"; interface IProtocolFeeController { /// @notice Returns the protocol fees for a pool given the conditions of this contract /// @param poolKey The pool key to identify the pool. The controller may want to use attributes on the pool /// to determine the protocol fee, hence the entire key is needed. function protocolFeeForPool(PoolKey memory poolKey) external view returns (uint24); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import {Currency} from "../types/Currency.sol"; import {IProtocolFeeController} from "../interfaces/IProtocolFeeController.sol"; import {PoolId} from "../types/PoolId.sol"; import {PoolKey} from "../types/PoolKey.sol"; interface IProtocolFees { /// @notice Thrown when not enough gas is provided to look up the protocol fee error ProtocolFeeCannotBeFetched(); /// @notice Thrown when protocol fee is set too high error InvalidProtocolFee(); /// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller. error InvalidCaller(); event ProtocolFeeControllerUpdated(address protocolFeeController); event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee); /// @notice Given a currency address, returns the protocol fees accrued in that currency function protocolFeesAccrued(Currency) external view returns (uint256); /// @notice Sets the protocol fee for the given pool function setProtocolFee(PoolKey memory key, uint24) external; /// @notice Sets the protocol fee controller function setProtocolFeeController(IProtocolFeeController) external; /// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected function collectProtocolFees(address, Currency, uint256) external returns (uint256); function protocolFeeController() external view returns (IProtocolFeeController); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @title BitMath /// @dev This library provides functionality for computing bit properties of an unsigned integer 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 /// @dev The function satisfies the property: /// x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1) /// @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); unchecked { if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } } /// @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 /// @dev The function satisfies the property: /// (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0) /// @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); unchecked { r = 255; if (x & type(uint128).max > 0) { r -= 128; } else { x >>= 128; } if (x & type(uint64).max > 0) { r -= 64; } else { x >>= 64; } if (x & type(uint32).max > 0) { r -= 32; } else { x >>= 32; } if (x & type(uint16).max > 0) { r -= 16; } else { x >>= 16; } if (x & type(uint8).max > 0) { r -= 8; } else { x >>= 8; } if (x & 0xf > 0) { r -= 4; } else { x >>= 4; } if (x & 0x3 > 0) { r -= 2; } else { x >>= 2; } if (x & 0x1 > 0) r -= 1; } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.4; /// @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 Reverts with the selector of a custom error in the scratch space function revertWith(bytes4 selector) internal pure { /// @solidity memory-safe-assembly assembly { 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 { /// @solidity memory-safe-assembly assembly { mstore(0, selector) mstore(0x04, addr) 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 { /// @solidity memory-safe-assembly assembly { mstore(0, selector) mstore(0x04, 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 { /// @solidity memory-safe-assembly assembly { mstore(0, selector) mstore(0x04, value) revert(0, 0x24) } } /// @dev Reverts with a custom error with two int24 arguments function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure { /// @solidity memory-safe-assembly assembly { mstore(0, selector) mstore(0x04, value1) mstore(0x24, value2) revert(0, 0x44) } } /// @dev Reverts with a custom error with two uint160 arguments function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure { /// @solidity memory-safe-assembly assembly { mstore(0, selector) mstore(0x04, value1) mstore(0x24, value2) revert(0, 0x44) } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @title FixedPoint128 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint128 { uint256 internal constant Q128 = 0x100000000000000000000000000000000; }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; /// @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 { 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 { 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 { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { 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 { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { 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 { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the preconditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) { unchecked { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) != 0) { require(++result > 0); } } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {PoolKey} from "../types/PoolKey.sol"; import {IHooks} from "../interfaces/IHooks.sol"; import {SafeCast} from "./SafeCast.sol"; import {LPFeeLibrary} from "./LPFeeLibrary.sol"; import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol"; import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "../types/BeforeSwapDelta.sol"; import {IPoolManager} from "../interfaces/IPoolManager.sol"; import {ParseBytes} from "./ParseBytes.sol"; import {CustomRevert} from "./CustomRevert.sol"; /// @notice V4 decides whether to invoke specific hooks by inspecting the lowest significant bits of the address that /// the hooks contract is deployed to. /// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400 /// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used. library Hooks { using LPFeeLibrary for uint24; using Hooks for IHooks; using SafeCast for int256; using BeforeSwapDeltaLibrary for BeforeSwapDelta; using ParseBytes for bytes; using CustomRevert for bytes4; uint160 internal constant ALL_HOOK_MASK = uint160((1 << 14) - 1); uint160 internal constant BEFORE_INITIALIZE_FLAG = 1 << 13; uint160 internal constant AFTER_INITIALIZE_FLAG = 1 << 12; uint160 internal constant BEFORE_ADD_LIQUIDITY_FLAG = 1 << 11; uint160 internal constant AFTER_ADD_LIQUIDITY_FLAG = 1 << 10; uint160 internal constant BEFORE_REMOVE_LIQUIDITY_FLAG = 1 << 9; uint160 internal constant AFTER_REMOVE_LIQUIDITY_FLAG = 1 << 8; uint160 internal constant BEFORE_SWAP_FLAG = 1 << 7; uint160 internal constant AFTER_SWAP_FLAG = 1 << 6; uint160 internal constant BEFORE_DONATE_FLAG = 1 << 5; uint160 internal constant AFTER_DONATE_FLAG = 1 << 4; uint160 internal constant BEFORE_SWAP_RETURNS_DELTA_FLAG = 1 << 3; uint160 internal constant AFTER_SWAP_RETURNS_DELTA_FLAG = 1 << 2; uint160 internal constant AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 1; uint160 internal constant AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 0; struct Permissions { bool beforeInitialize; bool afterInitialize; bool beforeAddLiquidity; bool afterAddLiquidity; bool beforeRemoveLiquidity; bool afterRemoveLiquidity; bool beforeSwap; bool afterSwap; bool beforeDonate; bool afterDonate; bool beforeSwapReturnDelta; bool afterSwapReturnDelta; bool afterAddLiquidityReturnDelta; bool afterRemoveLiquidityReturnDelta; } /// @notice Thrown if the address will not lead to the specified hook calls being called /// @param hooks The address of the hooks contract error HookAddressNotValid(address hooks); /// @notice Hook did not return its selector error InvalidHookResponse(); /// @notice thrown when a hook call fails error FailedHookCall(); /// @notice The hook's delta changed the swap from exactIn to exactOut or vice versa error HookDeltaExceedsSwapAmount(); /// @notice Utility function intended to be used in hook constructors to ensure /// the deployed hooks address causes the intended hooks to be called /// @param permissions The hooks that are intended to be called /// @dev permissions param is memory as the function will be called from constructors function validateHookPermissions(IHooks self, Permissions memory permissions) internal pure { if ( permissions.beforeInitialize != self.hasPermission(BEFORE_INITIALIZE_FLAG) || permissions.afterInitialize != self.hasPermission(AFTER_INITIALIZE_FLAG) || permissions.beforeAddLiquidity != self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG) || permissions.afterAddLiquidity != self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) || permissions.beforeRemoveLiquidity != self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG) || permissions.afterRemoveLiquidity != self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG) || permissions.beforeSwap != self.hasPermission(BEFORE_SWAP_FLAG) || permissions.afterSwap != self.hasPermission(AFTER_SWAP_FLAG) || permissions.beforeDonate != self.hasPermission(BEFORE_DONATE_FLAG) || permissions.afterDonate != self.hasPermission(AFTER_DONATE_FLAG) || permissions.beforeSwapReturnDelta != self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG) || permissions.afterSwapReturnDelta != self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG) || permissions.afterAddLiquidityReturnDelta != self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG) || permissions.afterRemoveLiquidityReturnDelta != self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG) ) { HookAddressNotValid.selector.revertWith(address(self)); } } /// @notice Ensures that the hook address includes at least one hook flag or dynamic fees, or is the 0 address /// @param self The hook to verify /// @return bool True if the hook address is valid function isValidHookAddress(IHooks self, uint24 fee) internal pure returns (bool) { // The hook can only have a flag to return a hook delta on an action if it also has the corresponding action flag if (!self.hasPermission(BEFORE_SWAP_FLAG) && self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) return false; if (!self.hasPermission(AFTER_SWAP_FLAG) && self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)) return false; if (!self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) && self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)) { return false; } if ( !self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG) && self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG) ) return false; // If there is no hook contract set, then fee cannot be dynamic // If a hook contract is set, it must have at least 1 flag set, or have a dynamic fee return address(self) == address(0) ? !fee.isDynamicFee() : (uint160(address(self)) & ALL_HOOK_MASK > 0 || fee.isDynamicFee()); } /// @notice performs a hook call using the given calldata on the given hook that doesnt return a delta /// @return result The complete data returned by the hook function callHook(IHooks self, bytes memory data) internal returns (bytes memory result) { /// @solidity memory-safe-assembly assembly { if iszero(call(gas(), self, 0, add(data, 0x20), mload(data), 0, 0)) { if iszero(returndatasize()) { // if the call failed without a revert reason, revert with `FailedHookCall()` mstore(0, 0x36bc48c5) revert(0x1c, 0x04) } // bubble up revert returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } // allocate result byte array from the free memory pointer result := mload(0x40) // store new free memory pointer at the end of the array padded to 32 bytes mstore(0x40, add(result, and(add(returndatasize(), 0x3f), not(0x1f)))) // store length in memory mstore(result, returndatasize()) // copy return data to result returndatacopy(add(result, 0x20), 0, returndatasize()) } // Check expected selector and returned selector match. if (result.parseSelector() != data.parseSelector()) InvalidHookResponse.selector.revertWith(); } /// @notice performs a hook call using the given calldata on the given hook /// @return delta The delta returned by the hook function callHookWithReturnDelta(IHooks self, bytes memory data, bool parseReturn) internal returns (int256 delta) { bytes memory result = callHook(self, data); // If this hook wasnt meant to return something, default to 0 delta if (!parseReturn) return 0; return result.parseReturnDelta(); } /// @notice modifier to prevent calling a hook if they initiated the action modifier noSelfCall(IHooks self) { if (msg.sender != address(self)) { _; } } /// @notice calls beforeInitialize hook if permissioned and validates return value function beforeInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96, bytes calldata hookData) internal noSelfCall(self) { if (self.hasPermission(BEFORE_INITIALIZE_FLAG)) { self.callHook( abi.encodeWithSelector(IHooks.beforeInitialize.selector, msg.sender, key, sqrtPriceX96, hookData) ); } } /// @notice calls afterInitialize hook if permissioned and validates return value function afterInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96, int24 tick, bytes calldata hookData) internal noSelfCall(self) { if (self.hasPermission(AFTER_INITIALIZE_FLAG)) { self.callHook( abi.encodeWithSelector(IHooks.afterInitialize.selector, msg.sender, key, sqrtPriceX96, tick, hookData) ); } } /// @notice calls beforeModifyLiquidity hook if permissioned and validates return value function beforeModifyLiquidity( IHooks self, PoolKey memory key, IPoolManager.ModifyLiquidityParams memory params, bytes calldata hookData ) internal noSelfCall(self) { if (params.liquidityDelta > 0 && self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)) { self.callHook(abi.encodeWithSelector(IHooks.beforeAddLiquidity.selector, msg.sender, key, params, hookData)); } else if (params.liquidityDelta <= 0 && self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)) { self.callHook( abi.encodeWithSelector(IHooks.beforeRemoveLiquidity.selector, msg.sender, key, params, hookData) ); } } /// @notice calls afterModifyLiquidity hook if permissioned and validates return value function afterModifyLiquidity( IHooks self, PoolKey memory key, IPoolManager.ModifyLiquidityParams memory params, BalanceDelta delta, bytes calldata hookData ) internal returns (BalanceDelta callerDelta, BalanceDelta hookDelta) { if (msg.sender == address(self)) return (delta, BalanceDeltaLibrary.ZERO_DELTA); callerDelta = delta; if (params.liquidityDelta > 0) { if (self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)) { hookDelta = BalanceDelta.wrap( self.callHookWithReturnDelta( abi.encodeCall(IHooks.afterAddLiquidity, (msg.sender, key, params, delta, hookData)), self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG) ) ); callerDelta = callerDelta - hookDelta; } } else { if (self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)) { hookDelta = BalanceDelta.wrap( self.callHookWithReturnDelta( abi.encodeCall(IHooks.afterRemoveLiquidity, (msg.sender, key, params, delta, hookData)), self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG) ) ); callerDelta = callerDelta - hookDelta; } } } /// @notice calls beforeSwap hook if permissioned and validates return value function beforeSwap(IHooks self, PoolKey memory key, IPoolManager.SwapParams memory params, bytes calldata hookData) internal returns (int256 amountToSwap, BeforeSwapDelta hookReturn, uint24 lpFeeOverride) { amountToSwap = params.amountSpecified; if (msg.sender == address(self)) return (amountToSwap, BeforeSwapDeltaLibrary.ZERO_DELTA, lpFeeOverride); if (self.hasPermission(BEFORE_SWAP_FLAG)) { bytes memory result = callHook(self, abi.encodeCall(IHooks.beforeSwap, (msg.sender, key, params, hookData))); // dynamic fee pools that do not want to override the cache fee, return 0 otherwise they return a valid fee with the override flag if (key.fee.isDynamicFee()) lpFeeOverride = result.parseFee(); // skip this logic for the case where the hook return is 0 if (self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) { hookReturn = BeforeSwapDelta.wrap(result.parseReturnDelta()); // any return in unspecified is passed to the afterSwap hook for handling int128 hookDeltaSpecified = hookReturn.getSpecifiedDelta(); // Update the swap amount according to the hook's return, and check that the swap type doesnt change (exact input/output) if (hookDeltaSpecified != 0) { bool exactInput = amountToSwap < 0; amountToSwap += hookDeltaSpecified; if (exactInput ? amountToSwap > 0 : amountToSwap < 0) { HookDeltaExceedsSwapAmount.selector.revertWith(); } } } } } /// @notice calls afterSwap hook if permissioned and validates return value function afterSwap( IHooks self, PoolKey memory key, IPoolManager.SwapParams memory params, BalanceDelta swapDelta, bytes calldata hookData, BeforeSwapDelta beforeSwapHookReturn ) internal returns (BalanceDelta, BalanceDelta) { if (msg.sender == address(self)) return (swapDelta, BalanceDeltaLibrary.ZERO_DELTA); int128 hookDeltaSpecified = beforeSwapHookReturn.getSpecifiedDelta(); int128 hookDeltaUnspecified = beforeSwapHookReturn.getUnspecifiedDelta(); if (self.hasPermission(AFTER_SWAP_FLAG)) { hookDeltaUnspecified += self.callHookWithReturnDelta( abi.encodeCall(IHooks.afterSwap, (msg.sender, key, params, swapDelta, hookData)), self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG) ).toInt128(); } BalanceDelta hookDelta; if (hookDeltaUnspecified != 0 || hookDeltaSpecified != 0) { hookDelta = (params.amountSpecified < 0 == params.zeroForOne) ? toBalanceDelta(hookDeltaSpecified, hookDeltaUnspecified) : toBalanceDelta(hookDeltaUnspecified, hookDeltaSpecified); // the caller has to pay for (or receive) the hook's delta swapDelta = swapDelta - hookDelta; } return (swapDelta, hookDelta); } /// @notice calls beforeDonate hook if permissioned and validates return value function beforeDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData) internal noSelfCall(self) { if (self.hasPermission(BEFORE_DONATE_FLAG)) { self.callHook( abi.encodeWithSelector(IHooks.beforeDonate.selector, msg.sender, key, amount0, amount1, hookData) ); } } /// @notice calls afterDonate hook if permissioned and validates return value function afterDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData) internal noSelfCall(self) { if (self.hasPermission(AFTER_DONATE_FLAG)) { self.callHook( abi.encodeWithSelector(IHooks.afterDonate.selector, msg.sender, key, amount0, amount1, hookData) ); } } function hasPermission(IHooks self, uint160 flag) internal pure returns (bool) { return uint160(address(self)) & flag != 0; } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @title Math library for liquidity library LiquidityMath { /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows /// @param x The liquidity before change /// @param y The delta by which liquidity should be changed /// @return z The liquidity delta function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) { assembly { z := add(x, y) if shr(128, z) { // revert SafeCastOverflow() mstore(0, 0x93dafdf1) revert(0x1c, 0x04) } } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; import {PoolKey} from "../types/PoolKey.sol"; import {CustomRevert} from "./CustomRevert.sol"; library LPFeeLibrary { using LPFeeLibrary for uint24; using CustomRevert for bytes4; /// @notice Thrown when the static or dynamic fee on a pool exceeds 100%. error FeeTooLarge(); // an lp fee of exactly 0b1000000... signals a dynamic fee pool. This isnt a valid static fee as it is > MAX_LP_FEE uint24 public constant DYNAMIC_FEE_FLAG = 0x800000; // 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; // mask to remove the override fee flag from a fee returned by the beforeSwaphook uint24 public constant REMOVE_OVERRIDE_MASK = 0xBFFFFF; // 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 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 maxmimum permitted fee 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 function validate(uint24 self) internal pure { if (!self.isValid()) FeeTooLarge.selector.revertWith(); } /// @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 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 (top bit of the uint24) function isOverride(uint24 self) internal pure returns (bool) { return self & OVERRIDE_FEE_FLAG != 0; } /// @notice returns a fee with the override flag removed 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) function removeOverrideFlagAndValidate(uint24 self) internal pure returns (uint24 fee) { fee = self.removeOverrideFlag(); fee.validate(); } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @notice Parses bytes returned from hooks and the byte selector used to check return selectors from hooks. /// @dev parseSelector also is used to parse the expected selector /// For parsing hook returns, note that all hooks return either bytes4 or (bytes4, 32-byte-delta) or (bytes4, 32-byte-delta, uint24). library ParseBytes { function parseSelector(bytes memory result) internal pure returns (bytes4 selector) { // equivalent: (selector,) = abi.decode(result, (bytes4, int256)); assembly { selector := mload(add(result, 0x20)) } } function parseFee(bytes memory result) internal pure returns (uint24 lpFee) { // equivalent: (,, lpFee) = abi.decode(result, (bytes4, int256, uint24)); assembly { lpFee := mload(add(result, 0x60)) } } function parseReturnDelta(bytes memory result) internal pure returns (int256 hookReturn) { // equivalent: (, hookReturnDelta) = abi.decode(result, (bytes4, int256)); assembly { hookReturn := mload(add(result, 0x40)) } } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.20; import {SafeCast} from "./SafeCast.sol"; import {TickBitmap} from "./TickBitmap.sol"; import {Position} from "./Position.sol"; import {FullMath} from "./FullMath.sol"; import {FixedPoint128} from "./FixedPoint128.sol"; import {TickMath} from "./TickMath.sol"; import {SqrtPriceMath} from "./SqrtPriceMath.sol"; import {SwapMath} from "./SwapMath.sol"; import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol"; import {Slot0} from "../types/Slot0.sol"; import {ProtocolFeeLibrary} from "./ProtocolFeeLibrary.sol"; import {LiquidityMath} from "./LiquidityMath.sol"; import {LPFeeLibrary} from "./LPFeeLibrary.sol"; import {CustomRevert} from "./CustomRevert.sol"; library Pool { using SafeCast for *; using TickBitmap for mapping(int16 => uint256); using Position for mapping(bytes32 => Position.Info); using Position for Position.Info; using Pool for State; using ProtocolFeeLibrary for uint24; using LPFeeLibrary for uint24; using CustomRevert for bytes4; /// @notice Thrown when tickLower is not below tickUpper /// @param tickLower The invalid tickLower /// @param tickUpper The invalid tickUpper error TicksMisordered(int24 tickLower, int24 tickUpper); /// @notice Thrown when tickLower is less than min tick /// @param tickLower The invalid tickLower error TickLowerOutOfBounds(int24 tickLower); /// @notice Thrown when tickUpper exceeds max tick /// @param tickUpper The invalid tickUpper error TickUpperOutOfBounds(int24 tickUpper); /// @notice For the tick spacing, the tick has too much liquidity error TickLiquidityOverflow(int24 tick); /// @notice Thrown when interacting with an uninitialized tick that must be initialized /// @param tick The uninitialized tick error TickNotInitialized(int24 tick); /// @notice Thrown when trying to initialize an already initialized pool error PoolAlreadyInitialized(); /// @notice Thrown when trying to interact with a non-initialized pool error PoolNotInitialized(); /// @notice Thrown when sqrtPriceLimitX96 on a swap has already exceeded its limit /// @param sqrtPriceCurrentX96 The invalid, already surpassed sqrtPriceLimitX96 /// @param sqrtPriceLimitX96 The surpassed price limit error PriceLimitAlreadyExceeded(uint160 sqrtPriceCurrentX96, uint160 sqrtPriceLimitX96); /// @notice Thrown when sqrtPriceLimitX96 lies outside of valid tick/price range /// @param sqrtPriceLimitX96 The invalid, out-of-bounds sqrtPriceLimitX96 error PriceLimitOutOfBounds(uint160 sqrtPriceLimitX96); /// @notice Thrown by donate if there is currently 0 liquidity, since the fees will not go to any liquidity providers error NoLiquidityToReceiveFees(); /// @notice Thrown when trying to swap with max lp fee and specifying an output amount error InvalidFeeForExactOut(); // info stored for each initialized individual tick struct TickInfo { // the total position liquidity that references this tick uint128 liquidityGross; // amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left), int128 liquidityNet; // fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) // only has relative meaning, not absolute — the value depends on when the tick is initialized uint256 feeGrowthOutside0X128; uint256 feeGrowthOutside1X128; } /// @dev The state of a pool struct State { Slot0 slot0; uint256 feeGrowthGlobal0X128; uint256 feeGrowthGlobal1X128; uint128 liquidity; mapping(int24 => TickInfo) ticks; mapping(int16 => uint256) tickBitmap; mapping(bytes32 => Position.Info) positions; } /// @dev Common checks for valid tick inputs. function checkTicks(int24 tickLower, int24 tickUpper) private pure { if (tickLower >= tickUpper) TicksMisordered.selector.revertWith(tickLower, tickUpper); if (tickLower < TickMath.MIN_TICK) TickLowerOutOfBounds.selector.revertWith(tickLower); if (tickUpper > TickMath.MAX_TICK) TickUpperOutOfBounds.selector.revertWith(tickUpper); } function initialize(State storage self, uint160 sqrtPriceX96, uint24 protocolFee, uint24 lpFee) internal returns (int24 tick) { if (self.slot0.sqrtPriceX96() != 0) PoolAlreadyInitialized.selector.revertWith(); tick = TickMath.getTickAtSqrtPrice(sqrtPriceX96); self.slot0 = Slot0.wrap(bytes32(0)).setSqrtPriceX96(sqrtPriceX96).setTick(tick).setProtocolFee(protocolFee) .setLpFee(lpFee); } function setProtocolFee(State storage self, uint24 protocolFee) internal { self.checkPoolInitialized(); self.slot0 = self.slot0.setProtocolFee(protocolFee); } /// @notice Only dynamic fee pools may update the lp fee. function setLPFee(State storage self, uint24 lpFee) internal { self.checkPoolInitialized(); self.slot0 = self.slot0.setLpFee(lpFee); } struct ModifyLiquidityParams { // the address that owns the position address owner; // the lower and upper tick of the position int24 tickLower; int24 tickUpper; // any change in liquidity int128 liquidityDelta; // the spacing between ticks int24 tickSpacing; // used to distinguish positions of the same owner, at the same tick range bytes32 salt; } struct ModifyLiquidityState { bool flippedLower; uint128 liquidityGrossAfterLower; bool flippedUpper; uint128 liquidityGrossAfterUpper; } /// @notice Effect changes to a position in a pool /// @dev PoolManager checks that the pool is initialized before calling /// @param params the position details and the change to the position's liquidity to effect /// @return delta the deltas of the token balances of the pool, from the liquidity change /// @return feeDelta the fees generated by the liquidity range function modifyLiquidity(State storage self, ModifyLiquidityParams memory params) internal returns (BalanceDelta delta, BalanceDelta feeDelta) { int128 liquidityDelta = params.liquidityDelta; int24 tickLower = params.tickLower; int24 tickUpper = params.tickUpper; checkTicks(tickLower, tickUpper); { ModifyLiquidityState memory state; // if we need to update the ticks, do it if (liquidityDelta != 0) { (state.flippedLower, state.liquidityGrossAfterLower) = updateTick(self, tickLower, liquidityDelta, false); (state.flippedUpper, state.liquidityGrossAfterUpper) = updateTick(self, tickUpper, liquidityDelta, true); // `>` and `>=` are logically equivalent here but `>=` is cheaper if (liquidityDelta >= 0) { uint128 maxLiquidityPerTick = tickSpacingToMaxLiquidityPerTick(params.tickSpacing); if (state.liquidityGrossAfterLower > maxLiquidityPerTick) { TickLiquidityOverflow.selector.revertWith(tickLower); } if (state.liquidityGrossAfterUpper > maxLiquidityPerTick) { TickLiquidityOverflow.selector.revertWith(tickUpper); } } if (state.flippedLower) { self.tickBitmap.flipTick(tickLower, params.tickSpacing); } if (state.flippedUpper) { self.tickBitmap.flipTick(tickUpper, params.tickSpacing); } } { (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) = getFeeGrowthInside(self, tickLower, tickUpper); Position.Info storage position = self.positions.get(params.owner, tickLower, tickUpper, params.salt); (uint256 feesOwed0, uint256 feesOwed1) = position.update(liquidityDelta, feeGrowthInside0X128, feeGrowthInside1X128); // Fees earned from LPing are added to the user's currency delta. feeDelta = toBalanceDelta(feesOwed0.toInt128(), feesOwed1.toInt128()); } // clear any tick data that is no longer needed if (liquidityDelta < 0) { if (state.flippedLower) { clearTick(self, tickLower); } if (state.flippedUpper) { clearTick(self, tickUpper); } } } if (liquidityDelta != 0) { Slot0 _slot0 = self.slot0; (int24 tick, uint160 sqrtPriceX96) = (_slot0.tick(), _slot0.sqrtPriceX96()); if (tick < tickLower) { // current tick is below the passed range; liquidity can only become in range by crossing from left to // right, when we'll need _more_ currency0 (it's becoming more valuable) so user must provide it delta = toBalanceDelta( SqrtPriceMath.getAmount0Delta( TickMath.getSqrtPriceAtTick(tickLower), TickMath.getSqrtPriceAtTick(tickUpper), liquidityDelta ).toInt128(), 0 ); } else if (tick < tickUpper) { delta = toBalanceDelta( SqrtPriceMath.getAmount0Delta(sqrtPriceX96, TickMath.getSqrtPriceAtTick(tickUpper), liquidityDelta) .toInt128(), SqrtPriceMath.getAmount1Delta(TickMath.getSqrtPriceAtTick(tickLower), sqrtPriceX96, liquidityDelta) .toInt128() ); self.liquidity = LiquidityMath.addDelta(self.liquidity, liquidityDelta); } else { // current tick is above the passed range; liquidity can only become in range by crossing from right to // left, when we'll need _more_ currency1 (it's becoming more valuable) so user must provide it delta = toBalanceDelta( 0, SqrtPriceMath.getAmount1Delta( TickMath.getSqrtPriceAtTick(tickLower), TickMath.getSqrtPriceAtTick(tickUpper), liquidityDelta ).toInt128() ); } } } // the top level state of the swap, the results of which are recorded in storage at the end struct SwapState { // the amount remaining to be swapped in/out of the input/output asset int256 amountSpecifiedRemaining; // the amount already swapped out/in of the output/input asset int256 amountCalculated; // current sqrt(price) uint160 sqrtPriceX96; // the tick associated with the current price int24 tick; // the global fee growth of the input token uint256 feeGrowthGlobalX128; // the current liquidity in range uint128 liquidity; } struct StepComputations { // the price at the beginning of the step uint160 sqrtPriceStartX96; // the next tick to swap to from the current tick in the swap direction int24 tickNext; // whether tickNext is initialized or not bool initialized; // sqrt(price) for the next tick (1/0) uint160 sqrtPriceNextX96; // how much is being swapped in in this step uint256 amountIn; // how much is being swapped out uint256 amountOut; // how much fee is being paid in uint256 feeAmount; } struct SwapParams { int24 tickSpacing; bool zeroForOne; int256 amountSpecified; uint160 sqrtPriceLimitX96; uint24 lpFeeOverride; } /// @notice Executes a swap against the state, and returns the amount deltas of the pool /// @dev PoolManager checks that the pool is initialized before calling function swap(State storage self, SwapParams memory params) internal returns (BalanceDelta result, uint256 feeForProtocol, uint24 swapFee, SwapState memory state) { Slot0 slot0Start = self.slot0; bool zeroForOne = params.zeroForOne; uint128 liquidityStart = self.liquidity; uint256 protocolFee = zeroForOne ? slot0Start.protocolFee().getZeroForOneFee() : slot0Start.protocolFee().getOneForZeroFee(); state.amountSpecifiedRemaining = params.amountSpecified; state.amountCalculated = 0; state.sqrtPriceX96 = slot0Start.sqrtPriceX96(); state.tick = slot0Start.tick(); state.feeGrowthGlobalX128 = zeroForOne ? self.feeGrowthGlobal0X128 : self.feeGrowthGlobal1X128; state.liquidity = liquidityStart; // if the beforeSwap hook returned a valid fee override, use that as the LP fee, otherwise load from storage { uint24 lpFee = params.lpFeeOverride.isOverride() ? params.lpFeeOverride.removeOverrideFlagAndValidate() : slot0Start.lpFee(); swapFee = protocolFee == 0 ? lpFee : uint24(protocolFee).calculateSwapFee(lpFee); } bool exactInput = params.amountSpecified < 0; if (!exactInput && (swapFee == LPFeeLibrary.MAX_LP_FEE)) { InvalidFeeForExactOut.selector.revertWith(); } if (params.amountSpecified == 0) return (BalanceDeltaLibrary.ZERO_DELTA, 0, swapFee, state); if (zeroForOne) { if (params.sqrtPriceLimitX96 >= slot0Start.sqrtPriceX96()) { PriceLimitAlreadyExceeded.selector.revertWith(slot0Start.sqrtPriceX96(), params.sqrtPriceLimitX96); } if (params.sqrtPriceLimitX96 <= TickMath.MIN_SQRT_PRICE) { PriceLimitOutOfBounds.selector.revertWith(params.sqrtPriceLimitX96); } } else { if (params.sqrtPriceLimitX96 <= slot0Start.sqrtPriceX96()) { PriceLimitAlreadyExceeded.selector.revertWith(slot0Start.sqrtPriceX96(), params.sqrtPriceLimitX96); } if (params.sqrtPriceLimitX96 >= TickMath.MAX_SQRT_PRICE) { PriceLimitOutOfBounds.selector.revertWith(params.sqrtPriceLimitX96); } } StepComputations memory step; // continue swapping as long as we haven't used the entire input/output and haven't reached the price limit while (!(state.amountSpecifiedRemaining == 0 || state.sqrtPriceX96 == params.sqrtPriceLimitX96)) { step.sqrtPriceStartX96 = state.sqrtPriceX96; (step.tickNext, step.initialized) = self.tickBitmap.nextInitializedTickWithinOneWord(state.tick, params.tickSpacing, zeroForOne); // ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds if (step.tickNext <= TickMath.MIN_TICK) { step.tickNext = TickMath.MIN_TICK; } if (step.tickNext >= TickMath.MAX_TICK) { step.tickNext = TickMath.MAX_TICK; } // get the price for the next tick step.sqrtPriceNextX96 = TickMath.getSqrtPriceAtTick(step.tickNext); // compute values to swap to the target tick, price limit, or point where input/output amount is exhausted (state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath.computeSwapStep( state.sqrtPriceX96, SwapMath.getSqrtPriceTarget(zeroForOne, step.sqrtPriceNextX96, params.sqrtPriceLimitX96), state.liquidity, state.amountSpecifiedRemaining, swapFee ); if (!exactInput) { unchecked { state.amountSpecifiedRemaining -= step.amountOut.toInt256(); } state.amountCalculated = state.amountCalculated - (step.amountIn + step.feeAmount).toInt256(); } else { // safe because we test that amountSpecified > amountIn + feeAmount in SwapMath unchecked { state.amountSpecifiedRemaining += (step.amountIn + step.feeAmount).toInt256(); } state.amountCalculated = state.amountCalculated + step.amountOut.toInt256(); } // if the protocol fee is on, calculate how much is owed, decrement feeAmount, and increment protocolFee if (protocolFee > 0) { unchecked { // step.amountIn does not include the swap fee, as it's already been taken from it, // so add it back to get the total amountIn and use that to calculate the amount of fees owed to the protocol uint256 delta = (step.amountIn + step.feeAmount) * protocolFee / ProtocolFeeLibrary.PIPS_DENOMINATOR; // subtract it from the total fee and add it to the protocol fee step.feeAmount -= delta; feeForProtocol += delta; } } // update global fee tracker if (state.liquidity > 0) { unchecked { state.feeGrowthGlobalX128 += FullMath.mulDiv(step.feeAmount, FixedPoint128.Q128, state.liquidity); } } // shift tick if we reached the next price if (state.sqrtPriceX96 == step.sqrtPriceNextX96) { // if the tick is initialized, run the tick transition if (step.initialized) { (uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = zeroForOne ? (state.feeGrowthGlobalX128, self.feeGrowthGlobal1X128) : (self.feeGrowthGlobal0X128, state.feeGrowthGlobalX128); int128 liquidityNet = Pool.crossTick(self, step.tickNext, feeGrowthGlobal0X128, feeGrowthGlobal1X128); // if we're moving leftward, we interpret liquidityNet as the opposite sign // safe because liquidityNet cannot be type(int128).min unchecked { if (zeroForOne) liquidityNet = -liquidityNet; } state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet); } // Equivalent to `state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;` unchecked { // cannot cast a bool to an int24 in Solidity int24 _zeroForOne; assembly { _zeroForOne := zeroForOne } state.tick = step.tickNext - _zeroForOne; } } else if (state.sqrtPriceX96 != step.sqrtPriceStartX96) { // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved state.tick = TickMath.getTickAtSqrtPrice(state.sqrtPriceX96); } } self.slot0 = slot0Start.setTick(state.tick).setSqrtPriceX96(state.sqrtPriceX96); // update liquidity if it changed if (liquidityStart != state.liquidity) self.liquidity = state.liquidity; // update fee growth global if (!zeroForOne) { self.feeGrowthGlobal1X128 = state.feeGrowthGlobalX128; } else { self.feeGrowthGlobal0X128 = state.feeGrowthGlobalX128; } unchecked { if (zeroForOne != exactInput) { result = toBalanceDelta( state.amountCalculated.toInt128(), (params.amountSpecified - state.amountSpecifiedRemaining).toInt128() ); } else { result = toBalanceDelta( (params.amountSpecified - state.amountSpecifiedRemaining).toInt128(), state.amountCalculated.toInt128() ); } } } /// @notice Donates the given amount of currency0 and currency1 to the pool function donate(State storage state, uint256 amount0, uint256 amount1) internal returns (BalanceDelta delta) { uint128 liquidity = state.liquidity; if (liquidity == 0) NoLiquidityToReceiveFees.selector.revertWith(); unchecked { // negation safe as amount0 and amount1 are always positive delta = toBalanceDelta(-(amount0.toInt128()), -(amount1.toInt128())); if (amount0 > 0) { state.feeGrowthGlobal0X128 += FullMath.mulDiv(amount0, FixedPoint128.Q128, liquidity); } if (amount1 > 0) { state.feeGrowthGlobal1X128 += FullMath.mulDiv(amount1, FixedPoint128.Q128, liquidity); } } } /// @notice Retrieves fee growth data /// @param self The Pool state struct /// @param tickLower The lower tick boundary of the position /// @param tickUpper The upper tick boundary of the position /// @return feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries /// @return feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries function getFeeGrowthInside(State storage self, int24 tickLower, int24 tickUpper) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) { TickInfo storage lower = self.ticks[tickLower]; TickInfo storage upper = self.ticks[tickUpper]; int24 tickCurrent = self.slot0.tick(); unchecked { if (tickCurrent < tickLower) { feeGrowthInside0X128 = lower.feeGrowthOutside0X128 - upper.feeGrowthOutside0X128; feeGrowthInside1X128 = lower.feeGrowthOutside1X128 - upper.feeGrowthOutside1X128; } else if (tickCurrent >= tickUpper) { feeGrowthInside0X128 = upper.feeGrowthOutside0X128 - lower.feeGrowthOutside0X128; feeGrowthInside1X128 = upper.feeGrowthOutside1X128 - lower.feeGrowthOutside1X128; } else { feeGrowthInside0X128 = self.feeGrowthGlobal0X128 - lower.feeGrowthOutside0X128 - upper.feeGrowthOutside0X128; feeGrowthInside1X128 = self.feeGrowthGlobal1X128 - lower.feeGrowthOutside1X128 - upper.feeGrowthOutside1X128; } } } /// @notice Updates a tick and returns true if the tick was flipped from initialized to uninitialized, or vice versa /// @param self The mapping containing all tick information for initialized ticks /// @param tick The tick that will be updated /// @param liquidityDelta A new amount of liquidity to be added (subtracted) when tick is crossed from left to right (right to left) /// @param upper true for updating a position's upper tick, or false for updating a position's lower tick /// @return flipped Whether the tick was flipped from initialized to uninitialized, or vice versa /// @return liquidityGrossAfter The total amount of liquidity for all positions that references the tick after the update function updateTick(State storage self, int24 tick, int128 liquidityDelta, bool upper) internal returns (bool flipped, uint128 liquidityGrossAfter) { TickInfo storage info = self.ticks[tick]; uint128 liquidityGrossBefore; int128 liquidityNetBefore; assembly { // load first slot of info which contains liquidityGross and liquidityNet packed // where the top 128 bits are liquidityNet and the bottom 128 bits are liquidityGross let liquidity := sload(info.slot) // slice off top 128 bits of liquidity (liquidityNet) to get just liquidityGross liquidityGrossBefore := shr(128, shl(128, liquidity)) // signed shift right 128 bits to get just liquidityNet liquidityNetBefore := sar(128, liquidity) } liquidityGrossAfter = LiquidityMath.addDelta(liquidityGrossBefore, liquidityDelta); flipped = (liquidityGrossAfter == 0) != (liquidityGrossBefore == 0); if (liquidityGrossBefore == 0) { // by convention, we assume that all growth before a tick was initialized happened _below_ the tick if (tick <= self.slot0.tick()) { info.feeGrowthOutside0X128 = self.feeGrowthGlobal0X128; info.feeGrowthOutside1X128 = self.feeGrowthGlobal1X128; } } // when the lower (upper) tick is crossed left to right (right to left), liquidity must be added (removed) int128 liquidityNet = upper ? liquidityNetBefore - liquidityDelta : liquidityNetBefore + liquidityDelta; assembly { // liquidityGrossAfter and liquidityNet are packed in the first slot of `info` // So we can store them with a single sstore by packing them ourselves first sstore( info.slot, // bitwise OR to pack liquidityGrossAfter and liquidityNet or( // liquidityGross is in the low bits, upper bits are already 0 liquidityGrossAfter, // shift liquidityNet to take the upper bits and lower bits get filled with 0 shl(128, liquidityNet) ) ) } } /// @notice Derives max liquidity per tick from given tick spacing /// @dev Executed within the pool constructor /// @param tickSpacing The amount of required tick separation, realized in multiples of `tickSpacing` /// e.g., a tickSpacing of 3 requires ticks to be initialized every 3rd tick i.e., ..., -6, -3, 0, 3, 6, ... /// @return result The max liquidity per tick function tickSpacingToMaxLiquidityPerTick(int24 tickSpacing) internal pure returns (uint128 result) { // Equivalent to: // int24 minTick = (TickMath.MIN_TICK / tickSpacing) * tickSpacing; // int24 maxTick = (TickMath.MAX_TICK / tickSpacing) * tickSpacing; // uint24 numTicks = uint24((maxTick - minTick) / tickSpacing) + 1; // return type(uint128).max / numTicks; int24 MAX_TICK = TickMath.MAX_TICK; int24 MIN_TICK = TickMath.MIN_TICK; // tick spacing will never be 0 since TickMath.MIN_TICK_SPACING is 1 assembly { let minTick := mul(sdiv(MIN_TICK, tickSpacing), tickSpacing) let maxTick := mul(sdiv(MAX_TICK, tickSpacing), tickSpacing) let numTicks := add(sdiv(sub(maxTick, minTick), tickSpacing), 1) result := div(sub(shl(128, 1), 1), numTicks) } } /// @notice Reverts if the given pool has not been initialized function checkPoolInitialized(State storage self) internal view { if (self.slot0.sqrtPriceX96() == 0) PoolNotInitialized.selector.revertWith(); } /// @notice Clears tick data /// @param self The mapping containing all initialized tick information for initialized ticks /// @param tick The tick that will be cleared function clearTick(State storage self, int24 tick) internal { delete self.ticks[tick]; } /// @notice Transitions to next tick as needed by price movement /// @param self The Pool state struct /// @param tick The destination tick of the transition /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0 /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1 /// @return liquidityNet The amount of liquidity added (subtracted) when tick is crossed from left to right (right to left) function crossTick(State storage self, int24 tick, uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) internal returns (int128 liquidityNet) { unchecked { TickInfo storage info = self.ticks[tick]; info.feeGrowthOutside0X128 = feeGrowthGlobal0X128 - info.feeGrowthOutside0X128; info.feeGrowthOutside1X128 = feeGrowthGlobal1X128 - info.feeGrowthOutside1X128; liquidityNet = info.liquidityNet; } } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.20; import {FullMath} from "./FullMath.sol"; import {FixedPoint128} from "./FixedPoint128.sol"; import {LiquidityMath} from "./LiquidityMath.sol"; import {CustomRevert} from "./CustomRevert.sol"; /// @title Position /// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary /// @dev Positions store additional state for tracking fees owed to the position library Position { using CustomRevert for bytes4; /// @notice Cannot update a position with no liquidity error CannotUpdateEmptyPosition(); // info stored for each user's position struct Info { // the amount of liquidity owned by this position uint128 liquidity; // fee growth per unit of liquidity as of the last update to liquidity or fees owed uint256 feeGrowthInside0LastX128; uint256 feeGrowthInside1LastX128; } /// @notice Returns the Info struct of a position, given an owner and position boundaries /// @param self The mapping containing all user positions /// @param owner The address of the position owner /// @param tickLower The lower tick boundary of the position /// @param tickUpper The upper tick boundary of the position /// @param salt A unique value to differentiate between multiple positions in the same range /// @return position The position info struct of the given owners' position function get(mapping(bytes32 => Info) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt) internal view returns (Info storage position) { // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt)) bytes32 positionKey; /// @solidity memory-safe-assembly assembly { mstore(0x26, salt) // [0x26, 0x46) mstore(0x06, tickUpper) // [0x23, 0x26) mstore(0x03, tickLower) // [0x20, 0x23) mstore(0, owner) // [0x0c, 0x20) positionKey := keccak256(0x0c, 0x3a) // len is 58 bytes mstore(0x26, 0) // rewrite 0x26 to 0 } position = self[positionKey]; } /// @notice Credits accumulated fees to a user's position /// @param self The individual position to update /// @param liquidityDelta The change in pool liquidity as a result of the position update /// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries /// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries /// @return feesOwed0 The amount of currency0 owed to the position owner /// @return feesOwed1 The amount of currency1 owed to the position owner function update( Info storage self, int128 liquidityDelta, uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128 ) internal returns (uint256 feesOwed0, uint256 feesOwed1) { uint128 liquidity = self.liquidity; if (liquidityDelta == 0) { // disallow pokes for 0 liquidity positions if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith(); } else { self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta); } // calculate accumulated fees. overflow in the subtraction of fee growth is expected unchecked { feesOwed0 = FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128); feesOwed1 = FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128); } // update the position self.feeGrowthInside0LastX128 = feeGrowthInside0X128; self.feeGrowthInside1LastX128 = feeGrowthInside1X128; } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; library ProtocolFeeLibrary { // Max protocol fee is 0.1% (1000 pips) uint16 public constant MAX_PROTOCOL_FEE = 1000; // Thresholds used for optimized bounds checks on protocol fees uint24 internal constant FEE_0_THRESHOLD = 1001; uint24 internal constant FEE_1_THRESHOLD = 1001 << 12; // the protocol fee is represented in hundredths of a bip uint256 internal constant PIPS_DENOMINATOR = 1_000_000; function getZeroForOneFee(uint24 self) internal pure returns (uint16) { return uint16(self & 0xfff); } function getOneForZeroFee(uint24 self) internal pure returns (uint16) { return uint16(self >> 12); } function isValidProtocolFee(uint24 self) internal pure returns (bool valid) { // Equivalent to: getZeroForOneFee(self) <= MAX_PROTOCOL_FEE && getOneForZeroFee(self) <= MAX_PROTOCOL_FEE assembly { let isZeroForOneFeeOk := lt(and(self, 0xfff), FEE_0_THRESHOLD) let isOneForZeroFeeOk := lt(self, FEE_1_THRESHOLD) valid := and(isZeroForOneFeeOk, isOneForZeroFeeOk) } } // The protocol fee is taken from the input amount first and then the LP fee is taken from the remaining // The swap fee is capped at 100% // Equivalent to protocolFee + lpFee(1_000_000 - protocolFee) / 1_000_000 function calculateSwapFee(uint24 self, uint24 lpFee) internal pure returns (uint24 swapFee) { // protocolFee + lpFee - (protocolFee * lpFee / 1_000_000). Div rounds up to favor LPs over the protocol. assembly { let numerator := mul(self, lpFee) let divRoundingUp := add(div(numerator, PIPS_DENOMINATOR), gt(mod(numerator, PIPS_DENOMINATOR), 0)) swapFee := sub(add(self, lpFee), divRoundingUp) } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { error SafeCastOverflow(); function _revertOverflow() private pure { /// @solidity memory-safe-assembly assembly { // Store the function selector of `SafeCastOverflow()`. mstore(0x00, 0x93dafdf1) // Revert with (offset, size). revert(0x1c, 0x04) } } /// @notice Cast a uint256 to a uint160, revert on overflow /// @param x The uint256 to be downcasted /// @return The downcasted integer, now type uint160 function toUint160(uint256 x) internal pure returns (uint160) { if (x >= 1 << 160) _revertOverflow(); return uint160(x); } /// @notice Cast a uint256 to a uint128, revert on overflow /// @param x The uint256 to be downcasted /// @return The downcasted integer, now type uint128 function toUint128(uint256 x) internal pure returns (uint128) { if (x >= 1 << 128) _revertOverflow(); return uint128(x); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param x The int256 to be downcasted /// @return The downcasted integer, now type int128 function toInt128(int256 x) internal pure returns (int128) { unchecked { if (((1 << 127) + uint256(x)) >> 128 == uint256(0)) return int128(x); _revertOverflow(); } } /// @notice Cast a uint256 to a int256, revert on overflow /// @param x The uint256 to be casted /// @return The casted integer, now type int256 function toInt256(uint256 x) internal pure returns (int256) { if (int256(x) >= 0) return int256(x); _revertOverflow(); } /// @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) _revertOverflow(); return int128(int256(x)); } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; import {SafeCast} from "./SafeCast.sol"; import {FullMath} from "./FullMath.sol"; import {UnsafeMath} from "./UnsafeMath.sol"; import {FixedPoint96} from "./FixedPoint96.sol"; /// @title Functions based on Q64.96 sqrt price and liquidity /// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas library SqrtPriceMath { using SafeCast for uint256; error InvalidPriceOrLiquidity(); error InvalidPrice(); error NotEnoughLiquidity(); error PriceOverflow(); /// @notice Gets the next sqrt price given a delta of currency0 /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the /// price less in order to not send too much output. /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96), /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount). /// @param sqrtPX96 The starting price, i.e. before accounting for the currency0 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of currency0 to add or remove from virtual reserves /// @param add Whether to add or remove the amount of currency0 /// @return The price after adding or removing amount, depending on add function getNextSqrtPriceFromAmount0RoundingUp(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add) internal pure returns (uint160) { // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price if (amount == 0) return sqrtPX96; uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; if (add) { unchecked { uint256 product = amount * sqrtPX96; if (product / amount == sqrtPX96) { uint256 denominator = numerator1 + product; if (denominator >= numerator1) { // always fits in 160 bits return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator)); } } } // denominator is checked for overflow return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96) + amount)); } else { unchecked { uint256 product = amount * sqrtPX96; // if the product overflows, we know the denominator underflows // in addition, we must check that the denominator does not underflow // equivalent: if (product / amount != sqrtPX96 || numerator1 <= product) revert PriceOverflow(); /// @solidity memory-safe-assembly assembly { if iszero(and(eq(div(product, amount), sqrtPX96), gt(numerator1, product))) { mstore(0, 0xf5c787f1) // selector for PriceOverflow() revert(0x1c, 0x04) } } uint256 denominator = numerator1 - product; return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160(); } } } /// @notice Gets the next sqrt price given a delta of currency1 /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the /// price less in order to not send too much output. /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity /// @param sqrtPX96 The starting price, i.e., before accounting for the currency1 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of currency1 to add, or remove, from virtual reserves /// @param add Whether to add, or remove, the amount of currency1 /// @return The price after adding or removing `amount` function getNextSqrtPriceFromAmount1RoundingDown(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add) internal pure returns (uint160) { // if we're adding (subtracting), rounding down requires rounding the quotient down (up) // in both cases, avoid a mulDiv for most inputs if (add) { uint256 quotient = ( amount <= type(uint160).max ? (amount << FixedPoint96.RESOLUTION) / liquidity : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity) ); return (uint256(sqrtPX96) + quotient).toUint160(); } else { uint256 quotient = ( amount <= type(uint160).max ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity) : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity) ); // equivalent: if (sqrtPX96 <= quotient) revert NotEnoughLiquidity(); /// @solidity memory-safe-assembly assembly { if iszero(gt(sqrtPX96, quotient)) { mstore(0, 0x4323a555) // selector for NotEnoughLiquidity() revert(0x1c, 0x04) } } // always fits 160 bits unchecked { return uint160(sqrtPX96 - quotient); } } } /// @notice Gets the next sqrt price given an input amount of currency0 or currency1 /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount /// @param liquidity The amount of usable liquidity /// @param amountIn How much of currency0, or currency1, is being swapped in /// @param zeroForOne Whether the amount in is currency0 or currency1 /// @return sqrtQX96 The price after adding the input amount to currency0 or currency1 function getNextSqrtPriceFromInput(uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne) internal pure returns (uint160 sqrtQX96) { // equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity(); /// @solidity memory-safe-assembly assembly { if or(iszero(sqrtPX96), iszero(liquidity)) { mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity() revert(0x1c, 0x04) } } // round to make sure that we don't pass the target price return zeroForOne ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true) : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true); } /// @notice Gets the next sqrt price given an output amount of currency0 or currency1 /// @dev Throws if price or liquidity are 0 or the next price is out of bounds /// @param sqrtPX96 The starting price before accounting for the output amount /// @param liquidity The amount of usable liquidity /// @param amountOut How much of currency0, or currency1, is being swapped out /// @param zeroForOne Whether the amount out is currency1 or currency0 /// @return sqrtQX96 The price after removing the output amount of currency0 or currency1 function getNextSqrtPriceFromOutput(uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne) internal pure returns (uint160 sqrtQX96) { // equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity(); /// @solidity memory-safe-assembly assembly { if or(iszero(sqrtPX96), iszero(liquidity)) { mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity() revert(0x1c, 0x04) } } // round to make sure that we pass the target price return zeroForOne ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false); } /// @notice Gets the amount0 delta between two prices /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper), /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower)) /// @param sqrtPriceAX96 A sqrt price /// @param sqrtPriceBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up or down /// @return amount0 Amount of currency0 required to cover a position of size liquidity between the two passed prices function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp) internal pure returns (uint256 amount0) { unchecked { if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96); // equivalent: if (sqrtPriceAX96 == 0) revert InvalidPrice(); /// @solidity memory-safe-assembly assembly { if iszero(sqrtPriceAX96) { mstore(0, 0x00bfc921) // selector for InvalidPrice() revert(0x1c, 0x04) } } uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; uint256 numerator2 = sqrtPriceBX96 - sqrtPriceAX96; return roundUp ? UnsafeMath.divRoundingUp(FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtPriceBX96), sqrtPriceAX96) : FullMath.mulDiv(numerator1, numerator2, sqrtPriceBX96) / sqrtPriceAX96; } } /// @notice Equivalent to: `a >= b ? a - b : b - a` function absDiff(uint160 a, uint160 b) internal pure returns (uint256 res) { assembly { let diff := sub(a, b) // mask = 0 if a >= b else -1 (all 1s) let mask := sar(255, diff) // if a >= b, res = a - b = 0 ^ (a - b) // if a < b, res = b - a = ~~(b - a) = ~(-(b - a) - 1) = ~(a - b - 1) = (-1) ^ (a - b - 1) // either way, res = mask ^ (a - b + mask) res := xor(mask, add(mask, diff)) } } /// @notice Gets the amount1 delta between two prices /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower)) /// @param sqrtPriceAX96 A sqrt price /// @param sqrtPriceBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up, or down /// @return amount1 Amount of currency1 required to cover a position of size liquidity between the two passed prices function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp) internal pure returns (uint256 amount1) { uint256 numerator = absDiff(sqrtPriceAX96, sqrtPriceBX96); uint256 denominator = FixedPoint96.Q96; uint256 _liquidity; assembly { // avoid implicit upcasting _liquidity := liquidity } /** * Equivalent to: * amount1 = roundUp * ? FullMath.mulDivRoundingUp(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96) * : FullMath.mulDiv(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96); * Cannot overflow because `type(uint128).max * type(uint160).max >> 96 < (1 << 192)`. */ amount1 = FullMath.mulDiv(_liquidity, numerator, denominator); assembly { amount1 := add(amount1, and(gt(mulmod(_liquidity, numerator, denominator), 0), roundUp)) } } /// @notice Helper that gets signed currency0 delta /// @param sqrtPriceAX96 A sqrt price /// @param sqrtPriceBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount0 delta /// @return amount0 Amount of currency0 corresponding to the passed liquidityDelta between the two prices function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity) internal pure returns (int256 amount0) { unchecked { return liquidity < 0 ? getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256() : -getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256(); } } /// @notice Helper that gets signed currency1 delta /// @param sqrtPriceAX96 A sqrt price /// @param sqrtPriceBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount1 delta /// @return amount1 Amount of currency1 corresponding to the passed liquidityDelta between the two prices function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity) internal pure returns (int256 amount1) { unchecked { return liquidity < 0 ? getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256() : -getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256(); } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.21; import {PoolId} from "../types/PoolId.sol"; import {IPoolManager} from "../interfaces/IPoolManager.sol"; import {Currency} from "../types/Currency.sol"; import {Position} from "./Position.sol"; library StateLibrary { // forge inspect src/PoolManager.sol:PoolManager storage --pretty // | Name | Type | Slot | Offset | Bytes | Contract | // |-----------------------|-----------------------------------------|------|--------|-------|---------------------------------| // | pools | mapping(PoolId => struct Pool.State) | 6 | 0 | 32 | src/PoolManager.sol:PoolManager | uint256 public constant POOLS_SLOT = 6; // index of feeGrowthGlobal0X128 in Pool.State uint256 public constant FEE_GROWTH_GLOBAL0_OFFSET = 1; // index of feeGrowthGlobal1X128 in Pool.State uint256 public constant FEE_GROWTH_GLOBAL1_OFFSET = 2; // index of liquidity in Pool.State uint256 public constant LIQUIDITY_OFFSET = 3; // index of TicksInfo mapping in Pool.State: mapping(int24 => TickInfo) ticks; uint256 public constant TICKS_OFFSET = 4; // index of tickBitmap mapping in Pool.State uint256 public constant TICK_BITMAP_OFFSET = 5; // index of Position.Info mapping in Pool.State: mapping(bytes32 => Position.Info) positions; uint256 public constant POSITIONS_OFFSET = 6; /** * @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee * @dev Corresponds to pools[poolId].slot0 * @param manager The pool manager contract. * @param poolId The ID of the pool. * @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision. * @return tick The current tick of the pool. * @return protocolFee The protocol fee of the pool. * @return lpFee The swap fee of the pool. */ function getSlot0(IPoolManager manager, PoolId poolId) internal view returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee) { // slot key of Pool.State value: `pools[poolId]` bytes32 stateSlot = _getPoolStateSlot(poolId); bytes32 data = manager.extsload(stateSlot); // 24 bits |24bits|24bits |24 bits|160 bits // 0x000000 |000bb8|000000 |ffff75 |0000000000000000fe3aa841ba359daa0ea9eff7 // ---------- | fee |protocolfee | tick | sqrtPriceX96 assembly { // bottom 160 bits of data sqrtPriceX96 := and(data, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) // next 24 bits of data tick := signextend(2, shr(160, data)) // next 24 bits of data protocolFee := and(shr(184, data), 0xFFFFFF) // last 24 bits of data lpFee := and(shr(208, data), 0xFFFFFF) } } /** * @notice Retrieves the tick information of a pool at a specific tick. * @dev Corresponds to pools[poolId].ticks[tick] * @param manager The pool manager contract. * @param poolId The ID of the pool. * @param tick The tick to retrieve information for. * @return liquidityGross The total position liquidity that references this tick * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left) * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) */ function getTickInfo(IPoolManager manager, PoolId poolId, int24 tick) internal view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128 ) { bytes32 slot = _getTickInfoSlot(poolId, tick); // read all 3 words of the TickInfo struct bytes memory data = manager.extsload(slot, 3); assembly { let firstWord := mload(add(data, 32)) liquidityNet := sar(128, firstWord) liquidityGross := and(firstWord, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) feeGrowthOutside0X128 := mload(add(data, 64)) feeGrowthOutside1X128 := mload(add(data, 96)) } } /** * @notice Retrieves the liquidity information of a pool at a specific tick. * @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo * @param manager The pool manager contract. * @param poolId The ID of the pool. * @param tick The tick to retrieve liquidity for. * @return liquidityGross The total position liquidity that references this tick * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left) */ function getTickLiquidity(IPoolManager manager, PoolId poolId, int24 tick) internal view returns (uint128 liquidityGross, int128 liquidityNet) { bytes32 slot = _getTickInfoSlot(poolId, tick); bytes32 value = manager.extsload(slot); assembly { liquidityNet := sar(128, value) liquidityGross := and(value, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) } } /** * @notice Retrieves the fee growth outside a tick range of a pool * @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo * @param manager The pool manager contract. * @param poolId The ID of the pool. * @param tick The tick to retrieve fee growth for. * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) */ function getTickFeeGrowthOutside(IPoolManager manager, PoolId poolId, int24 tick) internal view returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128) { bytes32 slot = _getTickInfoSlot(poolId, tick); // offset by 1 word, since the first word is liquidityGross + liquidityNet bytes memory data = manager.extsload(bytes32(uint256(slot) + 1), 2); assembly { feeGrowthOutside0X128 := mload(add(data, 32)) feeGrowthOutside1X128 := mload(add(data, 64)) } } /** * @notice Retrieves the global fee growth of a pool. * @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128 * @param manager The pool manager contract. * @param poolId The ID of the pool. * @return feeGrowthGlobal0 The global fee growth for token0. * @return feeGrowthGlobal1 The global fee growth for token1. */ function getFeeGrowthGlobals(IPoolManager manager, PoolId poolId) internal view returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1) { // slot key of Pool.State value: `pools[poolId]` bytes32 stateSlot = _getPoolStateSlot(poolId); // Pool.State, `uint256 feeGrowthGlobal0X128` bytes32 slot_feeGrowthGlobal0X128 = bytes32(uint256(stateSlot) + FEE_GROWTH_GLOBAL0_OFFSET); // read the 2 words of feeGrowthGlobal bytes memory data = manager.extsload(slot_feeGrowthGlobal0X128, 2); assembly { feeGrowthGlobal0 := mload(add(data, 32)) feeGrowthGlobal1 := mload(add(data, 64)) } } /** * @notice Retrieves total the liquidity of a pool. * @dev Corresponds to pools[poolId].liquidity * @param manager The pool manager contract. * @param poolId The ID of the pool. * @return liquidity The liquidity of the pool. */ function getLiquidity(IPoolManager manager, PoolId poolId) internal view returns (uint128 liquidity) { // slot key of Pool.State value: `pools[poolId]` bytes32 stateSlot = _getPoolStateSlot(poolId); // Pool.State: `uint128 liquidity` bytes32 slot = bytes32(uint256(stateSlot) + LIQUIDITY_OFFSET); liquidity = uint128(uint256(manager.extsload(slot))); } /** * @notice Retrieves the tick bitmap of a pool at a specific tick. * @dev Corresponds to pools[poolId].tickBitmap[tick] * @param manager The pool manager contract. * @param poolId The ID of the pool. * @param tick The tick to retrieve the bitmap for. * @return tickBitmap The bitmap of the tick. */ function getTickBitmap(IPoolManager manager, PoolId poolId, int16 tick) internal view returns (uint256 tickBitmap) { // slot key of Pool.State value: `pools[poolId]` bytes32 stateSlot = _getPoolStateSlot(poolId); // Pool.State: `mapping(int16 => uint256) tickBitmap;` bytes32 tickBitmapMapping = bytes32(uint256(stateSlot) + TICK_BITMAP_OFFSET); // slot id of the mapping key: `pools[poolId].tickBitmap[tick] bytes32 slot = keccak256(abi.encodePacked(int256(tick), tickBitmapMapping)); tickBitmap = uint256(manager.extsload(slot)); } /** * @notice Retrieves the position information of a pool at a specific position ID. * @dev Corresponds to pools[poolId].positions[positionId] * @param manager The pool manager contract. * @param poolId The ID of the pool. * @param positionId The ID of the position. * @return liquidity The liquidity of the position. * @return feeGrowthInside0LastX128 The fee growth inside the position for token0. * @return feeGrowthInside1LastX128 The fee growth inside the position for token1. */ function getPositionInfo(IPoolManager manager, PoolId poolId, bytes32 positionId) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) { bytes32 slot = _getPositionInfoSlot(poolId, positionId); // read all 3 words of the Position.Info struct bytes memory data = manager.extsload(slot, 3); assembly { liquidity := mload(add(data, 32)) feeGrowthInside0LastX128 := mload(add(data, 64)) feeGrowthInside1LastX128 := mload(add(data, 96)) } } function getPosition( IPoolManager manager, PoolId poolId, address owner, int24 tickLower, int24 tickUpper, bytes32 salt ) internal view returns (Position.Info memory) { // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt)) bytes32 positionKey; /// @solidity memory-safe-assembly assembly { mstore(0x26, salt) // [0x26, 0x46) mstore(0x06, tickUpper) // [0x23, 0x26) mstore(0x03, tickLower) // [0x20, 0x23) mstore(0, owner) // [0x0c, 0x20) positionKey := keccak256(0x0c, 0x3a) // len is 58 bytes mstore(0x26, 0) // rewrite 0x26 to 0 } (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) = getPositionInfo(manager, poolId, positionKey); return Position.Info({ liquidity: liquidity, feeGrowthInside0LastX128: feeGrowthInside0LastX128, feeGrowthInside1LastX128: feeGrowthInside1LastX128 }); } /** * @notice Retrieves the liquidity of a position. * @dev Corresponds to pools[poolId].positions[positionId].liquidity. A more gas efficient version of getPositionInfo * @param manager The pool manager contract. * @param poolId The ID of the pool. * @param positionId The ID of the position. * @return liquidity The liquidity of the position. */ function getPositionLiquidity(IPoolManager manager, PoolId poolId, bytes32 positionId) internal view returns (uint128 liquidity) { bytes32 slot = _getPositionInfoSlot(poolId, positionId); liquidity = uint128(uint256(manager.extsload(slot))); } /** * @notice Live calculate the fee growth inside a tick range of a pool * @dev pools[poolId].feeGrowthInside0LastX128 in Position.Info is cached and can become stale. This function will live calculate the feeGrowthInside * @param manager The pool manager contract. * @param poolId The ID of the pool. * @param tickLower The lower tick of the range. * @param tickUpper The upper tick of the range. * @return feeGrowthInside0X128 The fee growth inside the tick range for token0. * @return feeGrowthInside1X128 The fee growth inside the tick range for token1. */ function getFeeGrowthInside(IPoolManager manager, PoolId poolId, int24 tickLower, int24 tickUpper) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) { (uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = getFeeGrowthGlobals(manager, poolId); (uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128) = getTickFeeGrowthOutside(manager, poolId, tickLower); (uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128) = getTickFeeGrowthOutside(manager, poolId, tickUpper); (, int24 tickCurrent,,) = getSlot0(manager, poolId); unchecked { if (tickCurrent < tickLower) { feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128; feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128; } else if (tickCurrent >= tickUpper) { feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128; feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128; } else { feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128; feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128; } } } function _getPoolStateSlot(PoolId poolId) internal pure returns (bytes32) { return keccak256(abi.encodePacked(PoolId.unwrap(poolId), bytes32(POOLS_SLOT))); } function _getTickInfoSlot(PoolId poolId, int24 tick) internal pure returns (bytes32) { // slot key of Pool.State value: `pools[poolId]` bytes32 stateSlot = _getPoolStateSlot(poolId); // Pool.State: `mapping(int24 => TickInfo) ticks` bytes32 ticksMappingSlot = bytes32(uint256(stateSlot) + TICKS_OFFSET); // slot key of the tick key: `pools[poolId].ticks[tick] return keccak256(abi.encodePacked(int256(tick), ticksMappingSlot)); } function _getPositionInfoSlot(PoolId poolId, bytes32 positionId) internal pure returns (bytes32 slot) { // slot key of Pool.State value: `pools[poolId]` bytes32 stateSlot = _getPoolStateSlot(poolId); // Pool.State: `mapping(bytes32 => Position.Info) positions;` bytes32 positionMapping = bytes32(uint256(stateSlot) + POSITIONS_OFFSET); // slot of the mapping key: `pools[poolId].positions[positionId] return keccak256(abi.encodePacked(positionId, positionMapping)); } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; import {FullMath} from "./FullMath.sol"; import {SqrtPriceMath} from "./SqrtPriceMath.sol"; /// @title Computes the result of a swap within ticks /// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick. library SwapMath { uint256 internal constant MAX_FEE_PIPS = 1e6; /// @notice Computes the sqrt price target for the next swap step /// @param zeroForOne The direction of the swap, true for currency0 to currency1, false for currency1 to currency0 /// @param sqrtPriceNextX96 The Q64.96 sqrt price for the next initialized tick /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value /// after the swap. If one for zero, the price cannot be greater than this value after the swap /// @return sqrtPriceTargetX96 The price target for the next swap step function getSqrtPriceTarget(bool zeroForOne, uint160 sqrtPriceNextX96, uint160 sqrtPriceLimitX96) internal pure returns (uint160 sqrtPriceTargetX96) { assembly { // a flag to toggle between sqrtPriceNextX96 and sqrtPriceLimitX96 // when zeroForOne == true, nextOrLimit reduces to sqrtPriceNextX96 >= sqrtPriceLimitX96 // sqrtPriceTargetX96 = max(sqrtPriceNextX96, sqrtPriceLimitX96) // when zeroForOne == false, nextOrLimit reduces to sqrtPriceNextX96 < sqrtPriceLimitX96 // sqrtPriceTargetX96 = min(sqrtPriceNextX96, sqrtPriceLimitX96) let nextOrLimit := xor(lt(sqrtPriceNextX96, sqrtPriceLimitX96), zeroForOne) let symDiff := xor(sqrtPriceNextX96, sqrtPriceLimitX96) sqrtPriceTargetX96 := xor(sqrtPriceLimitX96, mul(symDiff, nextOrLimit)) } } /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap /// @dev If the swap's amountSpecified is negative, the combined fee and input amount will never exceed the absolute value of the remaining amount. /// @param sqrtPriceCurrentX96 The current sqrt price of the pool /// @param sqrtPriceTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred /// @param liquidity The usable liquidity /// @param amountRemaining How much input or output amount is remaining to be swapped in/out /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip /// @return sqrtPriceNextX96 The price after swapping the amount in/out, not to exceed the price target /// @return amountIn The amount to be swapped in, of either currency0 or currency1, based on the direction of the swap /// @return amountOut The amount to be received, of either currency0 or currency1, based on the direction of the swap /// @return feeAmount The amount of input that will be taken as a fee function computeSwapStep( uint160 sqrtPriceCurrentX96, uint160 sqrtPriceTargetX96, uint128 liquidity, int256 amountRemaining, uint24 feePips ) internal pure returns (uint160 sqrtPriceNextX96, uint256 amountIn, uint256 amountOut, uint256 feeAmount) { unchecked { uint256 _feePips = feePips; // upcast once and cache bool zeroForOne = sqrtPriceCurrentX96 >= sqrtPriceTargetX96; bool exactIn = amountRemaining < 0; if (exactIn) { uint256 amountRemainingLessFee = FullMath.mulDiv(uint256(-amountRemaining), MAX_FEE_PIPS - _feePips, MAX_FEE_PIPS); amountIn = zeroForOne ? SqrtPriceMath.getAmount0Delta(sqrtPriceTargetX96, sqrtPriceCurrentX96, liquidity, true) : SqrtPriceMath.getAmount1Delta(sqrtPriceCurrentX96, sqrtPriceTargetX96, liquidity, true); if (amountRemainingLessFee >= amountIn) { // `amountIn` is capped by the target price sqrtPriceNextX96 = sqrtPriceTargetX96; feeAmount = _feePips == MAX_FEE_PIPS ? amountIn : FullMath.mulDivRoundingUp(amountIn, _feePips, MAX_FEE_PIPS - _feePips); } else { sqrtPriceNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput( sqrtPriceCurrentX96, liquidity, amountRemainingLessFee, zeroForOne ); amountIn = zeroForOne ? SqrtPriceMath.getAmount0Delta(sqrtPriceNextX96, sqrtPriceCurrentX96, liquidity, true) : SqrtPriceMath.getAmount1Delta(sqrtPriceCurrentX96, sqrtPriceNextX96, liquidity, true); // we didn't reach the target, so take the remainder of the maximum input as fee feeAmount = uint256(-amountRemaining) - amountIn; } amountOut = zeroForOne ? SqrtPriceMath.getAmount1Delta(sqrtPriceNextX96, sqrtPriceCurrentX96, liquidity, false) : SqrtPriceMath.getAmount0Delta(sqrtPriceCurrentX96, sqrtPriceNextX96, liquidity, false); } else { amountOut = zeroForOne ? SqrtPriceMath.getAmount1Delta(sqrtPriceTargetX96, sqrtPriceCurrentX96, liquidity, false) : SqrtPriceMath.getAmount0Delta(sqrtPriceCurrentX96, sqrtPriceTargetX96, liquidity, false); if (uint256(amountRemaining) >= amountOut) { // `amountOut` is capped by the target price sqrtPriceNextX96 = sqrtPriceTargetX96; } else { // cap the output amount to not exceed the remaining output amount amountOut = uint256(amountRemaining); sqrtPriceNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(sqrtPriceCurrentX96, liquidity, amountOut, zeroForOne); } amountIn = zeroForOne ? SqrtPriceMath.getAmount0Delta(sqrtPriceNextX96, sqrtPriceCurrentX96, liquidity, true) : SqrtPriceMath.getAmount1Delta(sqrtPriceCurrentX96, sqrtPriceNextX96, liquidity, true); // `feePips` cannot be `MAX_FEE_PIPS` for exact out feeAmount = FullMath.mulDivRoundingUp(amountIn, _feePips, MAX_FEE_PIPS - _feePips); } } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import {BitMath} from "./BitMath.sol"; /// @title Packed tick initialized state library /// @notice Stores a packed mapping of tick index to its initialized state /// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word. library TickBitmap { /// @notice Thrown when the tick is not enumerated by the tick spacing /// @param tick the invalid tick /// @param tickSpacing The tick spacing of the pool error TickMisaligned(int24 tick, int24 tickSpacing); /// @dev round towards negative infinity function compress(int24 tick, int24 tickSpacing) internal pure returns (int24 compressed) { // compressed = tick / tickSpacing; // if (tick < 0 && tick % tickSpacing != 0) compressed--; assembly { compressed := sub( sdiv(tick, tickSpacing), // if (tick < 0 && tick % tickSpacing != 0) then tick % tickSpacing < 0, vice versa slt(smod(tick, tickSpacing), 0) ) } } /// @notice Computes the position in the mapping where the initialized bit for a tick lives /// @param tick The tick for which to compute the position /// @return wordPos The key in the mapping containing the word in which the bit is stored /// @return bitPos The bit position in the word where the flag is stored function position(int24 tick) internal pure returns (int16 wordPos, uint8 bitPos) { assembly { // signed arithmetic shift right wordPos := sar(8, tick) bitPos := and(tick, 0xff) } } /// @notice Flips the initialized state for a given tick from false to true, or vice versa /// @param self The mapping in which to flip the tick /// @param tick The tick to flip /// @param tickSpacing The spacing between usable ticks function flipTick(mapping(int16 => uint256) storage self, int24 tick, int24 tickSpacing) internal { /** * Equivalent to the following Solidity: * if (tick % tickSpacing != 0) revert TickMisaligned(tick, tickSpacing); * (int16 wordPos, uint8 bitPos) = position(tick / tickSpacing); * uint256 mask = 1 << bitPos; * self[wordPos] ^= mask; */ /// @solidity memory-safe-assembly assembly { // ensure that the tick is spaced if smod(tick, tickSpacing) { mstore(0, 0xd4d8f3e6) // selector for TickMisaligned(int24,int24) mstore(0x20, tick) mstore(0x40, tickSpacing) revert(0x1c, 0x44) } tick := sdiv(tick, tickSpacing) // calculate the storage slot corresponding to the tick // wordPos = tick >> 8 mstore(0, sar(8, tick)) mstore(0x20, self.slot) // the slot of self[wordPos] is keccak256(abi.encode(wordPos, self.slot)) let slot := keccak256(0, 0x40) // mask = 1 << bitPos = 1 << (tick % 256) // self[wordPos] ^= mask sstore(slot, xor(sload(slot), shl(and(tick, 0xff), 1))) } } /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either /// to the left (less than or equal to) or right (greater than) of the given tick /// @param self The mapping in which to compute the next initialized tick /// @param tick The starting tick /// @param tickSpacing The spacing between usable ticks /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick) /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks function nextInitializedTickWithinOneWord( mapping(int16 => uint256) storage self, int24 tick, int24 tickSpacing, bool lte ) internal view returns (int24 next, bool initialized) { unchecked { int24 compressed = compress(tick, tickSpacing); if (lte) { (int16 wordPos, uint8 bitPos) = position(compressed); // all the 1s at or to the right of the current bitPos uint256 mask = (1 << bitPos) - 1 + (1 << bitPos); uint256 masked = self[wordPos] & mask; // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word initialized = masked != 0; // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick next = initialized ? (compressed - int24(uint24(bitPos - BitMath.mostSignificantBit(masked)))) * tickSpacing : (compressed - int24(uint24(bitPos))) * tickSpacing; } else { // start from the word of the next tick, since the current tick state doesn't matter (int16 wordPos, uint8 bitPos) = position(++compressed); // all the 1s at or to the left of the bitPos uint256 mask = ~((1 << bitPos) - 1); uint256 masked = self[wordPos] & mask; // if there are no initialized ticks to the left of the current tick, return leftmost in the word initialized = masked != 0; // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick next = initialized ? (compressed + int24(uint24(BitMath.leastSignificantBit(masked) - bitPos))) * tickSpacing : (compressed + int24(uint24(type(uint8).max - bitPos))) * tickSpacing; } } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @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 { /// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK error InvalidTick(); /// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK error InvalidSqrtPrice(); /// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128 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 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 { // 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)) } // Equivalent: if (absTick > MAX_TICK) revert InvalidTick(); /// @solidity memory-safe-assembly assembly { if gt(absTick, MAX_TICK) { // store 4-byte selector of "InvalidTick()" at memory [0x1c, 0x20) mstore(0, 0xce8ef7fc) revert(0x1c, 0x04) } } // 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 { 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 { // 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 getPriceAtTick(tick) <= price /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getPriceAtTick 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 price is less than or equal to the input price 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 /// @solidity memory-safe-assembly assembly { // 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 gt(sub(sqrtPriceX96, MIN_SQRT_PRICE), MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) { // store 4-byte selector of "InvalidSqrtPrice()" at memory [0x1c, 0x20) mstore(0, 0x31efafe8) revert(0x1c, 0x04) } } uint256 price = uint256(sqrtPriceX96) << 32; uint256 r = price; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = price >> (msb - 127); else r = price << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { 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; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @title Math functions that do not check inputs or outputs /// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks library UnsafeMath { /// @notice Returns ceil(x / y) /// @dev division by 0 has unspecified behavior, and must be checked externally /// @param x The dividend /// @param y The divisor /// @return z The quotient, ceil(x / y) function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) { unchecked { assembly { z := add(div(x, y), gt(mod(x, y), 0)) } } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; 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 { 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 { 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 { 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); } library BalanceDeltaLibrary { BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0); function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) { assembly { _amount0 := sar(128, balanceDelta) } } function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) { assembly { _amount1 := signextend(15, balanceDelta) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import {BalanceDelta} from "./BalanceDelta.sol"; // 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) { /// @solidity memory-safe-assembly assembly { beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified)) } } library BeforeSwapDeltaLibrary { 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 { 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) { /// @solidity memory-safe-assembly assembly { deltaUnspecified := signextend(15, delta) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.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 Thrown when a native transfer fails error NativeTransferFailed(); /// @notice Thrown when an ERC20 transfer fails error ERC20TransferFailed(); Currency public constant NATIVE = Currency.wrap(address(0)); function transfer(Currency currency, address to, uint256 amount) internal { // altered from https://github.com/Vectorized/solady/blob/89101d53b7c8784cca935c1f2f6403639cee48b2/src/utils/SafeTransferLib.sol // modified custom error selectors if (currency.isNative()) { /// @solidity memory-safe-assembly assembly { // Transfer the ETH and revert if it fails. if iszero(call(gas(), to, amount, 0x00, 0x00, 0x00, 0x00)) { mstore(0x00, 0xf4b3b1bc) // `NativeTransferFailed()`. revert(0x1c, 0x04) } } } else { /// @solidity memory-safe-assembly assembly { mstore(0x14, to) // Store the `to` address in [0x20, 0x34). mstore(0x34, amount) // Store the `amount` argument in [0x34, 0x54). // Store the selector of `transfer(address,uint256)` in [0x10, 0x14). // also cleans the upper bits of `to` mstore(0x00, 0xa9059cbb000000000000000000000000) // Perform the transfer, reverting upon failure. if iszero( and( // The arguments of `and` are evaluated from right to left. or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing. call(gas(), currency, 0, 0x10, 0x44, 0x00, 0x20) ) ) { mstore(0x00, 0xf27f64e4) // `ERC20TransferFailed()`. revert(0x1c, 0x04) } mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten. } } } function balanceOfSelf(Currency currency) internal view returns (uint256) { if (currency.isNative()) { 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.isNative()) { return owner.balance; } else { return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner); } } function isNative(Currency currency) internal pure returns (bool) { return Currency.unwrap(currency) == Currency.unwrap(NATIVE); } function toId(Currency currency) internal pure returns (uint256) { return uint160(Currency.unwrap(currency)); } function fromId(uint256 id) internal pure returns (Currency) { return Currency.wrap(address(uint160(id))); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; 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) { /// @solidity memory-safe-assembly assembly { poolId := keccak256(poolKey, mul(32, 5)) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import {Currency} from "./Currency.sol"; import {IHooks} from "../interfaces/IHooks.sol"; /// @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 swap fee, capped at 1_000_000. If the first bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000 uint24 fee; /// @notice Ticks that involve positions must be a multiple of tick spacing int24 tickSpacing; /// @notice The hooks of the pool IHooks hooks; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; /** * @dev Slot0 is a packed version of solidity structure. * Using the packaged version saves gas by not storing the structure fields in memory slots. * * Layout: * 24 bits empty | 24 bits lpFee | 24 bits protocolFee | 24 bits tick | 160 bits sqrtPriceX96 * * Fields in the direction from the least significant bit: * * The current price * uint160 sqrtPriceX96; * * The current tick * int24 tick; * * Protocol fee, expressed in hundredths of a bip, upper 12 bits are for 1->0, and the lower 12 are for 0->1 * the maximum is 1000 - meaning the maximum protocol fee is 0.1% * the protocolFee is taken from the input first, then the lpFee is taken from the remaining input * uint24 protocolFee; * * Used for the lp fee, either static at initialize or dynamic via hook * uint24 lpFee; */ type Slot0 is bytes32; using Slot0Library for Slot0 global; library Slot0Library { uint160 internal constant MASK_160_BITS = 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; uint24 internal constant MASK_24_BITS = 0xFFFFFF; uint8 internal constant TICK_OFFSET = 160; uint8 internal constant PROTOCOL_FEE_OFFSET = 184; uint8 internal constant LP_FEE_OFFSET = 208; // #### GETTERS #### function sqrtPriceX96(Slot0 _packed) internal pure returns (uint160 _sqrtPriceX96) { /// @solidity memory-safe-assembly assembly { _sqrtPriceX96 := and(MASK_160_BITS, _packed) } } function tick(Slot0 _packed) internal pure returns (int24 _tick) { /// @solidity memory-safe-assembly assembly { _tick := signextend(2, shr(TICK_OFFSET, _packed)) } } function protocolFee(Slot0 _packed) internal pure returns (uint24 _protocolFee) { /// @solidity memory-safe-assembly assembly { _protocolFee := and(MASK_24_BITS, shr(PROTOCOL_FEE_OFFSET, _packed)) } } function lpFee(Slot0 _packed) internal pure returns (uint24 _lpFee) { /// @solidity memory-safe-assembly assembly { _lpFee := and(MASK_24_BITS, shr(LP_FEE_OFFSET, _packed)) } } // #### SETTERS #### function setSqrtPriceX96(Slot0 _packed, uint160 _sqrtPriceX96) internal pure returns (Slot0 _result) { /// @solidity memory-safe-assembly assembly { _result := or(and(not(MASK_160_BITS), _packed), and(MASK_160_BITS, _sqrtPriceX96)) } } function setTick(Slot0 _packed, int24 _tick) internal pure returns (Slot0 _result) { /// @solidity memory-safe-assembly assembly { _result := or(and(not(shl(TICK_OFFSET, MASK_24_BITS)), _packed), shl(TICK_OFFSET, and(MASK_24_BITS, _tick))) } } function setProtocolFee(Slot0 _packed, uint24 _protocolFee) internal pure returns (Slot0 _result) { /// @solidity memory-safe-assembly assembly { _result := or( and(not(shl(PROTOCOL_FEE_OFFSET, MASK_24_BITS)), _packed), shl(PROTOCOL_FEE_OFFSET, and(MASK_24_BITS, _protocolFee)) ) } } function setLpFee(Slot0 _packed, uint24 _lpFee) internal pure returns (Slot0 _result) { /// @solidity memory-safe-assembly assembly { _result := or(and(not(shl(LP_FEE_OFFSET, MASK_24_BITS)), _packed), shl(LP_FEE_OFFSET, and(MASK_24_BITS, _lpFee))) } } }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.20; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract LBPToken is ERC20 { constructor() ERC20("LBP Token", "LBP") { _mint(msg.sender, 1000000 * 10 ** 18); } }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.24; import {Quoter} from "../lib/v4-periphery/contracts/lens/Quoter.sol"; contract OnsenQuoter is Quoter { constructor(address manager) Quoter(manager) {} }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.20; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract USDC is ERC20 { constructor() ERC20("USD Coin", "USDC") { _mint(msg.sender, 10000000 * 10 ** 6); } function decimals() public pure override returns (uint8) { return 6; } function mint() external { _mint(msg.sender, 100 * 10 ** 6); } }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.20; contract WETH { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); event Deposit(address indexed dst, uint wad); event Withdrawal(address indexed src, uint wad); mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; receive() external payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); } function withdraw(uint wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; (bool success, ) = msg.sender.call{value: wad}(""); require(success, "WETH: ETH transfer failed"); emit Withdrawal(msg.sender, wad); } function totalSupply() public view returns (uint) { return address(this).balance; } function approve(address guy, uint wad) public returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != type(uint).max) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; emit Transfer(src, dst, wad); return true; } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import {IERC6909Claims} from "./interfaces/external/IERC6909Claims.sol"; /// @notice Minimalist and gas efficient standard ERC6909 implementation. /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC6909.sol) /// @dev Copied from the commit at 4b47a19038b798b4a33d9749d25e570443520647 /// @dev This contract has been modified from the implementation at the above link. abstract contract ERC6909 is 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); /*////////////////////////////////////////////////////////////// ERC6909 STORAGE //////////////////////////////////////////////////////////////*/ mapping(address => mapping(address => bool)) public isOperator; mapping(address => mapping(uint256 => uint256)) public balanceOf; mapping(address => mapping(address => mapping(uint256 => uint256))) public allowance; /*////////////////////////////////////////////////////////////// ERC6909 LOGIC //////////////////////////////////////////////////////////////*/ function transfer(address receiver, uint256 id, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender][id] -= amount; balanceOf[receiver][id] += amount; emit Transfer(msg.sender, msg.sender, receiver, id, amount); return true; } function transferFrom(address sender, address receiver, uint256 id, uint256 amount) public virtual returns (bool) { if (msg.sender != sender && !isOperator[sender][msg.sender]) { uint256 allowed = allowance[sender][msg.sender][id]; if (allowed != type(uint256).max) allowance[sender][msg.sender][id] = allowed - amount; } balanceOf[sender][id] -= amount; balanceOf[receiver][id] += amount; emit Transfer(msg.sender, sender, receiver, id, amount); return true; } function approve(address spender, uint256 id, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender][id] = amount; emit Approval(msg.sender, spender, id, amount); return true; } function setOperator(address operator, bool approved) public virtual returns (bool) { isOperator[msg.sender][operator] = approved; emit OperatorSet(msg.sender, operator, approved); return true; } /*////////////////////////////////////////////////////////////// ERC165 LOGIC //////////////////////////////////////////////////////////////*/ function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) { return interfaceId == 0x01ffc9a7 // ERC165 Interface ID for ERC165 || interfaceId == 0x0f632fb3; // ERC165 Interface ID for ERC6909 } /*////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address receiver, uint256 id, uint256 amount) internal virtual { balanceOf[receiver][id] += amount; emit Transfer(msg.sender, address(0), receiver, id, amount); } function _burn(address sender, uint256 id, uint256 amount) internal virtual { balanceOf[sender][id] -= amount; emit Transfer(msg.sender, sender, address(0), id, amount); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import {ERC6909} from "./ERC6909.sol"; /// @notice ERC6909Claims inherits ERC6909 and implements an internal burnFrom function abstract contract ERC6909Claims is ERC6909 { /// @notice Burn `amount` tokens of token type `id` from `from`. /// @dev if sender is not `from` they must be an operator or have sufficient allowance. /// @param from The address to burn tokens from. /// @param id The currency to burn. /// @param amount The amount to burn. function _burnFrom(address from, uint256 id, uint256 amount) internal { address sender = msg.sender; if (from != sender && !isOperator[from][sender]) { uint256 senderAllowance = allowance[from][sender][id]; if (senderAllowance != type(uint256).max) { allowance[from][sender][id] = senderAllowance - amount; } } _burn(from, id, amount); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import {IExtsload} from "./interfaces/IExtsload.sol"; /// @notice Enables public storage access for efficient state retrieval by external contracts. /// https://eips.ethereum.org/EIPS/eip-2330#rationale abstract contract Extsload is IExtsload { /// @inheritdoc IExtsload function extsload(bytes32 slot) external view returns (bytes32) { assembly ("memory-safe") { mstore(0, sload(slot)) return(0, 0x20) } } /// @inheritdoc IExtsload function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes memory) { assembly ("memory-safe") { // The abi offset of dynamic array in the returndata is 32. mstore(0, 0x20) // A left bit-shift of 5 is equivalent to multiplying by 32 but costs less gas. mstore(0x20, shl(5, nSlots)) let end := add(0x40, shl(5, nSlots)) for { let memptr := 0x40 } 1 {} { mstore(memptr, sload(startSlot)) memptr := add(memptr, 0x20) startSlot := add(startSlot, 1) if iszero(lt(memptr, end)) { break } } // The end offset is also the length of the returndata. return(0, end) } } /// @inheritdoc IExtsload function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory) { // since the function is external and enters a new call context and exits right // after execution, Solidity's memory management convention can be disregarded // and a direct slice of memory can be returned assembly ("memory-safe") { // Copy the abi offset of dynamic array and the length of the array to memory. calldatacopy(0, 0x04, 0x40) // A left bit-shift of 5 is equivalent to multiplying by 32 but costs less gas. let end := add(0x40, shl(5, slots.length)) let calldataptr := slots.offset // Return values will start at 64 while calldata offset is 68. for { let memptr := 0x40 } 1 {} { mstore(memptr, sload(calldataload(calldataptr))) memptr := add(memptr, 0x20) calldataptr := add(calldataptr, 0x20) if iszero(lt(memptr, end)) { break } } // The end offset is also the length of the returndata. return(0, end) } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.24; import {IExttload} from "./interfaces/IExttload.sol"; /// @notice Enables public transient storage access for efficient state retrieval by external contracts. /// https://eips.ethereum.org/EIPS/eip-2330#rationale abstract contract Exttload is IExttload { /// @inheritdoc IExttload function exttload(bytes32 slot) external view returns (bytes32) { assembly ("memory-safe") { mstore(0, tload(slot)) return(0, 0x20) } } /// @inheritdoc IExttload function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory) { // since the function is external and enters a new call context and exits right // after execution, Solidity's memory management convention can be disregarded // and a direct slice of memory can be returned assembly ("memory-safe") { // Copy the abi offset of dynamic array and the length of the array to memory. calldatacopy(0, 0x04, 0x40) // A left bit-shift of 5 is equivalent to multiplying by 32 but costs less gas. let end := add(0x40, shl(5, slots.length)) let calldataptr := slots.offset // Return values will start at 64 while calldata offset is 68. for { let memptr := 0x40 } 1 {} { mstore(memptr, tload(calldataload(calldataptr))) memptr := add(memptr, 0x20) calldataptr := add(calldataptr, 0x20) if iszero(lt(memptr, end)) { break } } // The end offset is also the length of the returndata. return(0, end) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; interface IUnlockCallback { /// @notice Called by the pool manager on `msg.sender` when the manager is unlocked /// @param data The data that was passed to the call to unlock /// @return Any data that you want to be returned from the unlock call function unlockCallback(bytes calldata data) external returns (bytes memory); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @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 the balance of a token /// @param account The account for which to look up the number of tokens it has, i.e. its balance /// @return The number of tokens held by the account function balanceOf(address account) external view returns (uint256); /// @notice Transfers the amount of token from the `msg.sender` to the recipient /// @param recipient The account that will receive the amount transferred /// @param amount The number of tokens to send from the sender to the recipient /// @return Returns true for a successful transfer, false for an unsuccessful transfer function transfer(address recipient, uint256 amount) external returns (bool); /// @notice Returns the current allowance given to a spender by an owner /// @param owner The account of the token owner /// @param spender The account of the token spender /// @return The current allowance granted by `owner` to `spender` function allowance(address owner, address spender) external view returns (uint256); /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount` /// @param spender The account which will be allowed to spend a given amount of the owners tokens /// @param amount The amount of tokens allowed to be used by `spender` /// @return Returns true for a successful approval, false for unsuccessful function approve(address spender, uint256 amount) external returns (bool); /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender` /// @param sender The account from which the transfer will be initiated /// @param recipient The recipient of the transfer /// @param amount The amount of the transfer /// @return Returns true for a successful transfer, false for unsuccessful function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`. /// @param from The account from which the tokens were sent, i.e. the balance decreased /// @param to The account to which the tokens were sent, i.e. the balance increased /// @param value The amount of tokens that were transferred event Transfer(address indexed from, address indexed to, uint256 value); /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes. /// @param owner The account that approved spending of its tokens /// @param spender The account for which the spending allowance was modified /// @param value The new allowance from the owner to the spender event Approval(address indexed owner, address indexed spender, uint256 value); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface IERC6909Claims { /// @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. 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. 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. function approve(address spender, uint256 id, uint256 amount) external returns (bool); /// @notice Sets or removes a spender as an operator for the caller. /// @param spender The address of the spender. /// @param approved The approval status. function setOperator(address spender, bool approved) external returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; 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 slot Key of slot to start sloading from /// @param nSlots Number of slots to load into return value /// @return value The value of the sload-ed slots concatenated as dynamic bytes function extsload(bytes32 slot, uint256 nSlots) external view returns (bytes memory value); /// @notice Called by external contracts to access sparse pool state /// @param slots List of slots to SLOAD from. /// @return values List of loaded values. function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.24; interface IExttload { /// @notice Called by external contracts to access transient storage of the contract /// @param slot Key of slot to tload /// @return value The value of the slot as bytes32 function exttload(bytes32 slot) external view returns (bytes32 value); /// @notice Called by external contracts to access sparse transient pool state /// @param slots List of slots to tload /// @return values List of loaded values function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {PoolKey} from "../types/PoolKey.sol"; import {BalanceDelta} from "../types/BalanceDelta.sol"; import {IPoolManager} from "./IPoolManager.sol"; import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol"; /// @notice The PoolManager contract decides whether to invoke specific hooks by inspecting the leading bits /// of the hooks contract address. For example, a 1 bit in the first bit of the address will /// cause the 'before swap' hook to be invoked. 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 /// @param hookData Arbitrary data handed into the PoolManager by the initializer to be be passed on to the hook /// @return bytes4 The function selector for the hook function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, bytes calldata hookData) 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 /// @param hookData Arbitrary data handed into the PoolManager by the initializer to be be passed on to the hook /// @return bytes4 The function selector for the hook function afterInitialize( address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick, bytes calldata hookData ) 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, IPoolManager.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 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, IPoolManager.ModifyLiquidityParams calldata params, BalanceDelta delta, 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 liquidty provider to be be passed on to the hook /// @return bytes4 The function selector for the hook function beforeRemoveLiquidity( address sender, PoolKey calldata key, IPoolManager.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 hookData Arbitrary data handed into the PoolManager by the liquidty 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, IPoolManager.ModifyLiquidityParams calldata params, BalanceDelta delta, 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, IPoolManager.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, IPoolManager.SwapParams calldata params, BalanceDelta delta, bytes calldata hookData ) external returns (bytes4, int128); /// @notice The hook called before donate /// @param sender The initial msg.sender for the donate call /// @param key The key for the pool /// @param amount0 The amount of token0 being donated /// @param amount1 The amount of token1 being donated /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook /// @return bytes4 The function selector for the hook function beforeDonate( address sender, PoolKey calldata key, uint256 amount0, uint256 amount1, bytes calldata hookData ) external returns (bytes4); /// @notice The hook called after donate /// @param sender The initial msg.sender for the donate call /// @param key The key for the pool /// @param amount0 The amount of token0 being donated /// @param amount1 The amount of token1 being donated /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook /// @return bytes4 The function selector for the hook function afterDonate( address sender, PoolKey calldata key, uint256 amount0, uint256 amount1, bytes calldata hookData ) external returns (bytes4); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {Currency} from "../types/Currency.sol"; import {PoolKey} from "../types/PoolKey.sol"; import {Pool} from "../libraries/Pool.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 {Position} from "../libraries/Position.sol"; import {IExtsload} from "./IExtsload.sol"; import {IExttload} from "./IExttload.sol"; 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(); /// @notice Pools must have a positive non-zero tickSpacing passed to #initialize error TickSpacingTooSmall(); /// @notice PoolKey must have currencies where address(currency0) < address(currency1) error CurrenciesOutOfOrderOrEqual(); /// @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 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 event Initialize( PoolId id, Currency indexed currency0, Currency indexed currency1, uint24 fee, int24 tickSpacing, IHooks hooks ); /// @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 event ModifyLiquidity( PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta ); /// @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 sender, int128 amount0, int128 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick, uint24 fee ); /// @notice Returns the constant representing the maximum tickSpacing for an initialized pool key function MAX_TICK_SPACING() external view returns (int24); /// @notice Returns the constant representing the minimum tickSpacing for an initialized pool key function MIN_TICK_SPACING() external view returns (int24); /// @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. function sync(Currency currency) external returns (uint256 balance); /// @notice Initialize the state for a given pool ID function initialize(PoolKey memory key, uint160 sqrtPriceX96, bytes calldata hookData) external returns (int24 tick); /// @notice All operations go through this function /// @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); 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 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 Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)` /// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal and fee deltas. /// @return feeDelta The balance delta of the fees generated in the liquidity range. Returned for informational purposes. function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData) external returns (BalanceDelta, BalanceDelta); struct SwapParams { bool zeroForOne; int256 amountSpecified; uint160 sqrtPriceLimitX96; } /// @notice Swap against the given pool /// @param key The pool to swap in /// @param params The parameters for swapping /// @param hookData Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)` /// @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); /// @notice Donate the given currency amounts to the pool with the given pool key function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData) external returns (BalanceDelta); /// @notice Called by the user to net out some value owed to the user /// @dev Can also be used as a mechanism for _free_ flash loans function take(Currency currency, address to, uint256 amount) external; /// @notice Called by the user to move value into ERC6909 balance function mint(address to, uint256 id, uint256 amount) external; /// @notice Called by the user to move value from ERC6909 balance function burn(address from, uint256 id, uint256 amount) external; /// @notice Called by the user to pay what is owed function settle(Currency token) external payable returns (uint256 paid); /// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees. function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import {PoolKey} from "../types/PoolKey.sol"; interface IProtocolFeeController { /// @notice Returns the protocol fees for a pool given the conditions of this contract /// @param poolKey The pool key to identify the pool. The controller may want to use attributes on the pool /// to determine the protocol fee, hence the entire key is needed. function protocolFeeForPool(PoolKey memory poolKey) external view returns (uint24); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import {Currency} from "../types/Currency.sol"; import {IProtocolFeeController} from "../interfaces/IProtocolFeeController.sol"; import {PoolId} from "../types/PoolId.sol"; import {PoolKey} from "../types/PoolKey.sol"; interface IProtocolFees { /// @notice Thrown when not enough gas is provided to look up the protocol fee error ProtocolFeeCannotBeFetched(); /// @notice Thrown when protocol fee is set too high error InvalidProtocolFee(); /// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller. error InvalidCaller(); event ProtocolFeeControllerUpdated(address protocolFeeController); event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee); /// @notice Given a currency address, returns the protocol fees accrued in that currency function protocolFeesAccrued(Currency) external view returns (uint256); /// @notice Sets the protocol fee for the given pool function setProtocolFee(PoolKey memory key, uint24) external; /// @notice Sets the protocol fee controller function setProtocolFeeController(IProtocolFeeController) external; /// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected function collectProtocolFees(address, Currency, uint256) external returns (uint256); function protocolFeeController() external view returns (IProtocolFeeController); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @title BitMath /// @dev This library provides functionality for computing bit properties of an unsigned integer 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 /// @dev The function satisfies the property: /// x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1) /// @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); unchecked { if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } } /// @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 /// @dev The function satisfies the property: /// (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0) /// @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); unchecked { r = 255; if (x & type(uint128).max > 0) { r -= 128; } else { x >>= 128; } if (x & type(uint64).max > 0) { r -= 64; } else { x >>= 64; } if (x & type(uint32).max > 0) { r -= 32; } else { x >>= 32; } if (x & type(uint16).max > 0) { r -= 16; } else { x >>= 16; } if (x & type(uint8).max > 0) { r -= 8; } else { x >>= 8; } if (x & 0xf > 0) { r -= 4; } else { x >>= 4; } if (x & 0x3 > 0) { r -= 2; } else { x >>= 2; } if (x & 0x1 > 0) r -= 1; } } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.20; import {Currency} from "../types/Currency.sol"; /// @title a library to store callers' currency deltas in transient storage /// @dev this library implements the equivalent of a mapping, as transient storage can only be accessed in assembly library CurrencyDelta { /// @notice calculates which storage slot a delta should be stored in for a given caller and currency function _computeSlot(address caller_, Currency currency) internal pure returns (bytes32 hashSlot) { assembly ("memory-safe") { mstore(0, caller_) mstore(32, currency) hashSlot := keccak256(0, 64) } } /// @notice sets a new currency delta for a given caller and currency function setDelta(Currency currency, address caller, int256 delta) internal { bytes32 hashSlot = _computeSlot(caller, currency); assembly { tstore(hashSlot, delta) } } /// @notice gets a new currency delta for a given caller and currency function getDelta(Currency currency, address caller) internal view returns (int256 delta) { bytes32 hashSlot = _computeSlot(caller, currency); assembly { delta := tload(hashSlot) } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.4; /// @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 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, addr) 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, 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, value) 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") { mstore(0, selector) mstore(0x04, value1) mstore(0x24, value2) revert(0, 0x44) } } /// @dev Reverts with a custom error with two uint160 arguments function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure { assembly ("memory-safe") { mstore(0, selector) mstore(0x04, value1) mstore(0x24, value2) revert(0, 0x44) } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @title FixedPoint128 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint128 { uint256 internal constant Q128 = 0x100000000000000000000000000000000; }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; /// @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 { 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 { 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 { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { 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 { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { 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 { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the preconditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) { unchecked { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) != 0) { require(++result > 0); } } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {PoolKey} from "../types/PoolKey.sol"; import {IHooks} from "../interfaces/IHooks.sol"; import {SafeCast} from "./SafeCast.sol"; import {LPFeeLibrary} from "./LPFeeLibrary.sol"; import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol"; import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "../types/BeforeSwapDelta.sol"; import {IPoolManager} from "../interfaces/IPoolManager.sol"; import {ParseBytes} from "./ParseBytes.sol"; import {CustomRevert} from "./CustomRevert.sol"; /// @notice V4 decides whether to invoke specific hooks by inspecting the lowest significant bits of the address that /// the hooks contract is deployed to. /// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400 /// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used. library Hooks { using LPFeeLibrary for uint24; using Hooks for IHooks; using SafeCast for int256; using BeforeSwapDeltaLibrary for BeforeSwapDelta; using ParseBytes for bytes; using CustomRevert for bytes4; uint160 internal constant ALL_HOOK_MASK = uint160((1 << 14) - 1); uint160 internal constant BEFORE_INITIALIZE_FLAG = 1 << 13; uint160 internal constant AFTER_INITIALIZE_FLAG = 1 << 12; uint160 internal constant BEFORE_ADD_LIQUIDITY_FLAG = 1 << 11; uint160 internal constant AFTER_ADD_LIQUIDITY_FLAG = 1 << 10; uint160 internal constant BEFORE_REMOVE_LIQUIDITY_FLAG = 1 << 9; uint160 internal constant AFTER_REMOVE_LIQUIDITY_FLAG = 1 << 8; uint160 internal constant BEFORE_SWAP_FLAG = 1 << 7; uint160 internal constant AFTER_SWAP_FLAG = 1 << 6; uint160 internal constant BEFORE_DONATE_FLAG = 1 << 5; uint160 internal constant AFTER_DONATE_FLAG = 1 << 4; uint160 internal constant BEFORE_SWAP_RETURNS_DELTA_FLAG = 1 << 3; uint160 internal constant AFTER_SWAP_RETURNS_DELTA_FLAG = 1 << 2; uint160 internal constant AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 1; uint160 internal constant AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 0; struct Permissions { bool beforeInitialize; bool afterInitialize; bool beforeAddLiquidity; bool afterAddLiquidity; bool beforeRemoveLiquidity; bool afterRemoveLiquidity; bool beforeSwap; bool afterSwap; bool beforeDonate; bool afterDonate; bool beforeSwapReturnDelta; bool afterSwapReturnDelta; bool afterAddLiquidityReturnDelta; bool afterRemoveLiquidityReturnDelta; } /// @notice Thrown if the address will not lead to the specified hook calls being called /// @param hooks The address of the hooks contract error HookAddressNotValid(address hooks); /// @notice Hook did not return its selector error InvalidHookResponse(); /// @notice thrown when a hook call fails error FailedHookCall(); /// @notice The hook's delta changed the swap from exactIn to exactOut or vice versa error HookDeltaExceedsSwapAmount(); /// @notice Utility function intended to be used in hook constructors to ensure /// the deployed hooks address causes the intended hooks to be called /// @param permissions The hooks that are intended to be called /// @dev permissions param is memory as the function will be called from constructors function validateHookPermissions(IHooks self, Permissions memory permissions) internal pure { if ( permissions.beforeInitialize != self.hasPermission(BEFORE_INITIALIZE_FLAG) || permissions.afterInitialize != self.hasPermission(AFTER_INITIALIZE_FLAG) || permissions.beforeAddLiquidity != self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG) || permissions.afterAddLiquidity != self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) || permissions.beforeRemoveLiquidity != self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG) || permissions.afterRemoveLiquidity != self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG) || permissions.beforeSwap != self.hasPermission(BEFORE_SWAP_FLAG) || permissions.afterSwap != self.hasPermission(AFTER_SWAP_FLAG) || permissions.beforeDonate != self.hasPermission(BEFORE_DONATE_FLAG) || permissions.afterDonate != self.hasPermission(AFTER_DONATE_FLAG) || permissions.beforeSwapReturnDelta != self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG) || permissions.afterSwapReturnDelta != self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG) || permissions.afterAddLiquidityReturnDelta != self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG) || permissions.afterRemoveLiquidityReturnDelta != self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG) ) { HookAddressNotValid.selector.revertWith(address(self)); } } /// @notice Ensures that the hook address includes at least one hook flag or dynamic fees, or is the 0 address /// @param self The hook to verify /// @return bool True if the hook address is valid function isValidHookAddress(IHooks self, uint24 fee) internal pure returns (bool) { // The hook can only have a flag to return a hook delta on an action if it also has the corresponding action flag if (!self.hasPermission(BEFORE_SWAP_FLAG) && self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) return false; if (!self.hasPermission(AFTER_SWAP_FLAG) && self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)) return false; if (!self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) && self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)) { return false; } if ( !self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG) && self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG) ) return false; // If there is no hook contract set, then fee cannot be dynamic // If a hook contract is set, it must have at least 1 flag set, or have a dynamic fee return address(self) == address(0) ? !fee.isDynamicFee() : (uint160(address(self)) & ALL_HOOK_MASK > 0 || fee.isDynamicFee()); } /// @notice performs a hook call using the given calldata on the given hook that doesnt return a delta /// @return result The complete data returned by the hook function callHook(IHooks self, bytes memory data) internal returns (bytes memory result) { assembly ("memory-safe") { if iszero(call(gas(), self, 0, add(data, 0x20), mload(data), 0, 0)) { if iszero(returndatasize()) { // if the call failed without a revert reason, revert with `FailedHookCall()` mstore(0, 0x36bc48c5) revert(0x1c, 0x04) } // bubble up revert returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } // allocate result byte array from the free memory pointer result := mload(0x40) // store new free memory pointer at the end of the array padded to 32 bytes mstore(0x40, add(result, and(add(returndatasize(), 0x3f), not(0x1f)))) // store length in memory mstore(result, returndatasize()) // copy return data to result returndatacopy(add(result, 0x20), 0, returndatasize()) } // Check expected selector and returned selector match. if (result.parseSelector() != data.parseSelector()) InvalidHookResponse.selector.revertWith(); } /// @notice performs a hook call using the given calldata on the given hook /// @return delta The delta returned by the hook function callHookWithReturnDelta(IHooks self, bytes memory data, bool parseReturn) internal returns (int256 delta) { bytes memory result = callHook(self, data); // If this hook wasnt meant to return something, default to 0 delta if (!parseReturn) return 0; return result.parseReturnDelta(); } /// @notice modifier to prevent calling a hook if they initiated the action modifier noSelfCall(IHooks self) { if (msg.sender != address(self)) { _; } } /// @notice calls beforeInitialize hook if permissioned and validates return value function beforeInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96, bytes calldata hookData) internal noSelfCall(self) { if (self.hasPermission(BEFORE_INITIALIZE_FLAG)) { self.callHook( abi.encodeWithSelector(IHooks.beforeInitialize.selector, msg.sender, key, sqrtPriceX96, hookData) ); } } /// @notice calls afterInitialize hook if permissioned and validates return value function afterInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96, int24 tick, bytes calldata hookData) internal noSelfCall(self) { if (self.hasPermission(AFTER_INITIALIZE_FLAG)) { self.callHook( abi.encodeWithSelector(IHooks.afterInitialize.selector, msg.sender, key, sqrtPriceX96, tick, hookData) ); } } /// @notice calls beforeModifyLiquidity hook if permissioned and validates return value function beforeModifyLiquidity( IHooks self, PoolKey memory key, IPoolManager.ModifyLiquidityParams memory params, bytes calldata hookData ) internal noSelfCall(self) { if (params.liquidityDelta > 0 && self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)) { self.callHook(abi.encodeWithSelector(IHooks.beforeAddLiquidity.selector, msg.sender, key, params, hookData)); } else if (params.liquidityDelta <= 0 && self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)) { self.callHook( abi.encodeWithSelector(IHooks.beforeRemoveLiquidity.selector, msg.sender, key, params, hookData) ); } } /// @notice calls afterModifyLiquidity hook if permissioned and validates return value function afterModifyLiquidity( IHooks self, PoolKey memory key, IPoolManager.ModifyLiquidityParams memory params, BalanceDelta delta, bytes calldata hookData ) internal returns (BalanceDelta callerDelta, BalanceDelta hookDelta) { if (msg.sender == address(self)) return (delta, BalanceDeltaLibrary.ZERO_DELTA); callerDelta = delta; if (params.liquidityDelta > 0) { if (self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)) { hookDelta = BalanceDelta.wrap( self.callHookWithReturnDelta( abi.encodeCall(IHooks.afterAddLiquidity, (msg.sender, key, params, delta, hookData)), self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG) ) ); callerDelta = callerDelta - hookDelta; } } else { if (self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)) { hookDelta = BalanceDelta.wrap( self.callHookWithReturnDelta( abi.encodeCall(IHooks.afterRemoveLiquidity, (msg.sender, key, params, delta, hookData)), self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG) ) ); callerDelta = callerDelta - hookDelta; } } } /// @notice calls beforeSwap hook if permissioned and validates return value function beforeSwap(IHooks self, PoolKey memory key, IPoolManager.SwapParams memory params, bytes calldata hookData) internal returns (int256 amountToSwap, BeforeSwapDelta hookReturn, uint24 lpFeeOverride) { amountToSwap = params.amountSpecified; if (msg.sender == address(self)) return (amountToSwap, BeforeSwapDeltaLibrary.ZERO_DELTA, lpFeeOverride); if (self.hasPermission(BEFORE_SWAP_FLAG)) { bytes memory result = callHook(self, abi.encodeCall(IHooks.beforeSwap, (msg.sender, key, params, hookData))); // dynamic fee pools that do not want to override the cache fee, return 0 otherwise they return a valid fee with the override flag if (key.fee.isDynamicFee()) lpFeeOverride = result.parseFee(); // skip this logic for the case where the hook return is 0 if (self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) { hookReturn = BeforeSwapDelta.wrap(result.parseReturnDelta()); // any return in unspecified is passed to the afterSwap hook for handling int128 hookDeltaSpecified = hookReturn.getSpecifiedDelta(); // Update the swap amount according to the hook's return, and check that the swap type doesnt change (exact input/output) if (hookDeltaSpecified != 0) { bool exactInput = amountToSwap < 0; amountToSwap += hookDeltaSpecified; if (exactInput ? amountToSwap > 0 : amountToSwap < 0) { HookDeltaExceedsSwapAmount.selector.revertWith(); } } } } } /// @notice calls afterSwap hook if permissioned and validates return value function afterSwap( IHooks self, PoolKey memory key, IPoolManager.SwapParams memory params, BalanceDelta swapDelta, bytes calldata hookData, BeforeSwapDelta beforeSwapHookReturn ) internal returns (BalanceDelta, BalanceDelta) { if (msg.sender == address(self)) return (swapDelta, BalanceDeltaLibrary.ZERO_DELTA); int128 hookDeltaSpecified = beforeSwapHookReturn.getSpecifiedDelta(); int128 hookDeltaUnspecified = beforeSwapHookReturn.getUnspecifiedDelta(); if (self.hasPermission(AFTER_SWAP_FLAG)) { hookDeltaUnspecified += self.callHookWithReturnDelta( abi.encodeCall(IHooks.afterSwap, (msg.sender, key, params, swapDelta, hookData)), self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG) ).toInt128(); } BalanceDelta hookDelta; if (hookDeltaUnspecified != 0 || hookDeltaSpecified != 0) { hookDelta = (params.amountSpecified < 0 == params.zeroForOne) ? toBalanceDelta(hookDeltaSpecified, hookDeltaUnspecified) : toBalanceDelta(hookDeltaUnspecified, hookDeltaSpecified); // the caller has to pay for (or receive) the hook's delta swapDelta = swapDelta - hookDelta; } return (swapDelta, hookDelta); } /// @notice calls beforeDonate hook if permissioned and validates return value function beforeDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData) internal noSelfCall(self) { if (self.hasPermission(BEFORE_DONATE_FLAG)) { self.callHook( abi.encodeWithSelector(IHooks.beforeDonate.selector, msg.sender, key, amount0, amount1, hookData) ); } } /// @notice calls afterDonate hook if permissioned and validates return value function afterDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData) internal noSelfCall(self) { if (self.hasPermission(AFTER_DONATE_FLAG)) { self.callHook( abi.encodeWithSelector(IHooks.afterDonate.selector, msg.sender, key, amount0, amount1, hookData) ); } } function hasPermission(IHooks self, uint160 flag) internal pure returns (bool) { return uint160(address(self)) & flag != 0; } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @title Math library for liquidity library LiquidityMath { /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows /// @param x The liquidity before change /// @param y The delta by which liquidity should be changed /// @return z The liquidity delta function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) { assembly ("memory-safe") { z := add(x, y) if shr(128, z) { // revert SafeCastOverflow() mstore(0, 0x93dafdf1) revert(0x1c, 0x04) } } } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.20; import {IHooks} from "../interfaces/IHooks.sol"; /// @notice This is a temporary library that allows us to use transient storage (tstore/tload) /// TODO: This library can be deleted when we have the transient keyword support in solidity. library Lock { // The slot holding the unlocked state, transiently. bytes32(uint256(keccak256("Unlocked")) - 1) bytes32 constant IS_UNLOCKED_SLOT = 0xc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab23; function unlock() internal { assembly { // unlock tstore(IS_UNLOCKED_SLOT, true) } } function lock() internal { assembly { tstore(IS_UNLOCKED_SLOT, false) } } function isUnlocked() internal view returns (bool unlocked) { assembly { unlocked := tload(IS_UNLOCKED_SLOT) } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; import {PoolKey} from "../types/PoolKey.sol"; import {CustomRevert} from "./CustomRevert.sol"; library LPFeeLibrary { using LPFeeLibrary for uint24; using CustomRevert for bytes4; /// @notice Thrown when the static or dynamic fee on a pool exceeds 100%. error FeeTooLarge(); // an lp fee of exactly 0b1000000... signals a dynamic fee pool. This isnt a valid static fee as it is > MAX_LP_FEE uint24 public constant DYNAMIC_FEE_FLAG = 0x800000; // 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; // mask to remove the override fee flag from a fee returned by the beforeSwaphook uint24 public constant REMOVE_OVERRIDE_MASK = 0xBFFFFF; // 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 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 maxmimum permitted fee 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 function validate(uint24 self) internal pure { if (!self.isValid()) FeeTooLarge.selector.revertWith(); } /// @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 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) function isOverride(uint24 self) internal pure returns (bool) { return self & OVERRIDE_FEE_FLAG != 0; } /// @notice returns a fee with the override flag removed 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) function removeOverrideFlagAndValidate(uint24 self) internal pure returns (uint24 fee) { fee = self.removeOverrideFlag(); fee.validate(); } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.20; import {IHooks} from "../interfaces/IHooks.sol"; /// @notice This is a temporary library that allows us to use transient storage (tstore/tload) /// for the nonzero delta count. /// TODO: This library can be deleted when we have the transient keyword support in solidity. library NonZeroDeltaCount { // The slot holding the number of nonzero deltas. bytes32(uint256(keccak256("NonzeroDeltaCount")) - 1) bytes32 constant NONZERO_DELTA_COUNT_SLOT = 0x7d4b3164c6e45b97e7d87b7125a44c5828d005af88f9d751cfd78729c5d99a0b; function read() internal view returns (uint256 count) { assembly { count := tload(NONZERO_DELTA_COUNT_SLOT) } } function increment() internal { assembly { let count := tload(NONZERO_DELTA_COUNT_SLOT) count := add(count, 1) tstore(NONZERO_DELTA_COUNT_SLOT, count) } } /// @notice Potential to underflow. /// Current usage ensures this will not happen because we call decrement with known boundaries (only up to the number of times we call increment). function decrement() internal { assembly { let count := tload(NONZERO_DELTA_COUNT_SLOT) count := sub(count, 1) tstore(NONZERO_DELTA_COUNT_SLOT, count) } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @notice Parses bytes returned from hooks and the byte selector used to check return selectors from hooks. /// @dev parseSelector also is used to parse the expected selector /// For parsing hook returns, note that all hooks return either bytes4 or (bytes4, 32-byte-delta) or (bytes4, 32-byte-delta, uint24). library ParseBytes { function parseSelector(bytes memory result) internal pure returns (bytes4 selector) { // equivalent: (selector,) = abi.decode(result, (bytes4, int256)); assembly ("memory-safe") { selector := mload(add(result, 0x20)) } } function parseFee(bytes memory result) internal pure returns (uint24 lpFee) { // equivalent: (,, lpFee) = abi.decode(result, (bytes4, int256, uint24)); assembly ("memory-safe") { lpFee := mload(add(result, 0x60)) } } function parseReturnDelta(bytes memory result) internal pure returns (int256 hookReturn) { // equivalent: (, hookReturnDelta) = abi.decode(result, (bytes4, int256)); assembly ("memory-safe") { hookReturn := mload(add(result, 0x40)) } } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.20; import {SafeCast} from "./SafeCast.sol"; import {TickBitmap} from "./TickBitmap.sol"; import {Position} from "./Position.sol"; import {FullMath} from "./FullMath.sol"; import {FixedPoint128} from "./FixedPoint128.sol"; import {TickMath} from "./TickMath.sol"; import {SqrtPriceMath} from "./SqrtPriceMath.sol"; import {SwapMath} from "./SwapMath.sol"; import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol"; import {Slot0} from "../types/Slot0.sol"; import {ProtocolFeeLibrary} from "./ProtocolFeeLibrary.sol"; import {LiquidityMath} from "./LiquidityMath.sol"; import {LPFeeLibrary} from "./LPFeeLibrary.sol"; import {CustomRevert} from "./CustomRevert.sol"; library Pool { using SafeCast for *; using TickBitmap for mapping(int16 => uint256); using Position for mapping(bytes32 => Position.Info); using Position for Position.Info; using Pool for State; using ProtocolFeeLibrary for uint24; using LPFeeLibrary for uint24; using CustomRevert for bytes4; /// @notice Thrown when tickLower is not below tickUpper /// @param tickLower The invalid tickLower /// @param tickUpper The invalid tickUpper error TicksMisordered(int24 tickLower, int24 tickUpper); /// @notice Thrown when tickLower is less than min tick /// @param tickLower The invalid tickLower error TickLowerOutOfBounds(int24 tickLower); /// @notice Thrown when tickUpper exceeds max tick /// @param tickUpper The invalid tickUpper error TickUpperOutOfBounds(int24 tickUpper); /// @notice For the tick spacing, the tick has too much liquidity error TickLiquidityOverflow(int24 tick); /// @notice Thrown when interacting with an uninitialized tick that must be initialized /// @param tick The uninitialized tick error TickNotInitialized(int24 tick); /// @notice Thrown when trying to initialize an already initialized pool error PoolAlreadyInitialized(); /// @notice Thrown when trying to interact with a non-initialized pool error PoolNotInitialized(); /// @notice Thrown when sqrtPriceLimitX96 on a swap has already exceeded its limit /// @param sqrtPriceCurrentX96 The invalid, already surpassed sqrtPriceLimitX96 /// @param sqrtPriceLimitX96 The surpassed price limit error PriceLimitAlreadyExceeded(uint160 sqrtPriceCurrentX96, uint160 sqrtPriceLimitX96); /// @notice Thrown when sqrtPriceLimitX96 lies outside of valid tick/price range /// @param sqrtPriceLimitX96 The invalid, out-of-bounds sqrtPriceLimitX96 error PriceLimitOutOfBounds(uint160 sqrtPriceLimitX96); /// @notice Thrown by donate if there is currently 0 liquidity, since the fees will not go to any liquidity providers error NoLiquidityToReceiveFees(); /// @notice Thrown when trying to swap with max lp fee and specifying an output amount error InvalidFeeForExactOut(); // info stored for each initialized individual tick struct TickInfo { // the total position liquidity that references this tick uint128 liquidityGross; // amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left), int128 liquidityNet; // fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) // only has relative meaning, not absolute — the value depends on when the tick is initialized uint256 feeGrowthOutside0X128; uint256 feeGrowthOutside1X128; } /// @dev The state of a pool struct State { Slot0 slot0; uint256 feeGrowthGlobal0X128; uint256 feeGrowthGlobal1X128; uint128 liquidity; mapping(int24 => TickInfo) ticks; mapping(int16 => uint256) tickBitmap; mapping(bytes32 => Position.Info) positions; } /// @dev Common checks for valid tick inputs. function checkTicks(int24 tickLower, int24 tickUpper) private pure { if (tickLower >= tickUpper) TicksMisordered.selector.revertWith(tickLower, tickUpper); if (tickLower < TickMath.MIN_TICK) TickLowerOutOfBounds.selector.revertWith(tickLower); if (tickUpper > TickMath.MAX_TICK) TickUpperOutOfBounds.selector.revertWith(tickUpper); } function initialize(State storage self, uint160 sqrtPriceX96, uint24 protocolFee, uint24 lpFee) internal returns (int24 tick) { if (self.slot0.sqrtPriceX96() != 0) PoolAlreadyInitialized.selector.revertWith(); tick = TickMath.getTickAtSqrtPrice(sqrtPriceX96); self.slot0 = Slot0.wrap(bytes32(0)).setSqrtPriceX96(sqrtPriceX96).setTick(tick).setProtocolFee(protocolFee) .setLpFee(lpFee); } function setProtocolFee(State storage self, uint24 protocolFee) internal { self.checkPoolInitialized(); self.slot0 = self.slot0.setProtocolFee(protocolFee); } /// @notice Only dynamic fee pools may update the lp fee. function setLPFee(State storage self, uint24 lpFee) internal { self.checkPoolInitialized(); self.slot0 = self.slot0.setLpFee(lpFee); } struct ModifyLiquidityParams { // the address that owns the position address owner; // the lower and upper tick of the position int24 tickLower; int24 tickUpper; // any change in liquidity int128 liquidityDelta; // the spacing between ticks int24 tickSpacing; // used to distinguish positions of the same owner, at the same tick range bytes32 salt; } struct ModifyLiquidityState { bool flippedLower; uint128 liquidityGrossAfterLower; bool flippedUpper; uint128 liquidityGrossAfterUpper; } /// @notice Effect changes to a position in a pool /// @dev PoolManager checks that the pool is initialized before calling /// @param params the position details and the change to the position's liquidity to effect /// @return delta the deltas of the token balances of the pool, from the liquidity change /// @return feeDelta the fees generated by the liquidity range function modifyLiquidity(State storage self, ModifyLiquidityParams memory params) internal returns (BalanceDelta delta, BalanceDelta feeDelta) { int128 liquidityDelta = params.liquidityDelta; int24 tickLower = params.tickLower; int24 tickUpper = params.tickUpper; checkTicks(tickLower, tickUpper); { ModifyLiquidityState memory state; // if we need to update the ticks, do it if (liquidityDelta != 0) { (state.flippedLower, state.liquidityGrossAfterLower) = updateTick(self, tickLower, liquidityDelta, false); (state.flippedUpper, state.liquidityGrossAfterUpper) = updateTick(self, tickUpper, liquidityDelta, true); // `>` and `>=` are logically equivalent here but `>=` is cheaper if (liquidityDelta >= 0) { uint128 maxLiquidityPerTick = tickSpacingToMaxLiquidityPerTick(params.tickSpacing); if (state.liquidityGrossAfterLower > maxLiquidityPerTick) { TickLiquidityOverflow.selector.revertWith(tickLower); } if (state.liquidityGrossAfterUpper > maxLiquidityPerTick) { TickLiquidityOverflow.selector.revertWith(tickUpper); } } if (state.flippedLower) { self.tickBitmap.flipTick(tickLower, params.tickSpacing); } if (state.flippedUpper) { self.tickBitmap.flipTick(tickUpper, params.tickSpacing); } } { (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) = getFeeGrowthInside(self, tickLower, tickUpper); Position.Info storage position = self.positions.get(params.owner, tickLower, tickUpper, params.salt); (uint256 feesOwed0, uint256 feesOwed1) = position.update(liquidityDelta, feeGrowthInside0X128, feeGrowthInside1X128); // Fees earned from LPing are added to the user's currency delta. feeDelta = toBalanceDelta(feesOwed0.toInt128(), feesOwed1.toInt128()); } // clear any tick data that is no longer needed if (liquidityDelta < 0) { if (state.flippedLower) { clearTick(self, tickLower); } if (state.flippedUpper) { clearTick(self, tickUpper); } } } if (liquidityDelta != 0) { Slot0 _slot0 = self.slot0; (int24 tick, uint160 sqrtPriceX96) = (_slot0.tick(), _slot0.sqrtPriceX96()); if (tick < tickLower) { // current tick is below the passed range; liquidity can only become in range by crossing from left to // right, when we'll need _more_ currency0 (it's becoming more valuable) so user must provide it delta = toBalanceDelta( SqrtPriceMath.getAmount0Delta( TickMath.getSqrtPriceAtTick(tickLower), TickMath.getSqrtPriceAtTick(tickUpper), liquidityDelta ).toInt128(), 0 ); } else if (tick < tickUpper) { delta = toBalanceDelta( SqrtPriceMath.getAmount0Delta(sqrtPriceX96, TickMath.getSqrtPriceAtTick(tickUpper), liquidityDelta) .toInt128(), SqrtPriceMath.getAmount1Delta(TickMath.getSqrtPriceAtTick(tickLower), sqrtPriceX96, liquidityDelta) .toInt128() ); self.liquidity = LiquidityMath.addDelta(self.liquidity, liquidityDelta); } else { // current tick is above the passed range; liquidity can only become in range by crossing from right to // left, when we'll need _more_ currency1 (it's becoming more valuable) so user must provide it delta = toBalanceDelta( 0, SqrtPriceMath.getAmount1Delta( TickMath.getSqrtPriceAtTick(tickLower), TickMath.getSqrtPriceAtTick(tickUpper), liquidityDelta ).toInt128() ); } } } // the top level state of the swap, the results of which are recorded in storage at the end struct SwapState { // the amount remaining to be swapped in/out of the input/output asset int256 amountSpecifiedRemaining; // the amount already swapped out/in of the output/input asset int256 amountCalculated; // current sqrt(price) uint160 sqrtPriceX96; // the tick associated with the current price int24 tick; // the global fee growth of the input token uint256 feeGrowthGlobalX128; // the current liquidity in range uint128 liquidity; } struct StepComputations { // the price at the beginning of the step uint160 sqrtPriceStartX96; // the next tick to swap to from the current tick in the swap direction int24 tickNext; // whether tickNext is initialized or not bool initialized; // sqrt(price) for the next tick (1/0) uint160 sqrtPriceNextX96; // how much is being swapped in in this step uint256 amountIn; // how much is being swapped out uint256 amountOut; // how much fee is being paid in uint256 feeAmount; } struct SwapParams { int24 tickSpacing; bool zeroForOne; int256 amountSpecified; uint160 sqrtPriceLimitX96; uint24 lpFeeOverride; } /// @notice Executes a swap against the state, and returns the amount deltas of the pool /// @dev PoolManager checks that the pool is initialized before calling function swap(State storage self, SwapParams memory params) internal returns (BalanceDelta result, uint256 feeForProtocol, uint24 swapFee, SwapState memory state) { Slot0 slot0Start = self.slot0; bool zeroForOne = params.zeroForOne; uint128 liquidityStart = self.liquidity; uint256 protocolFee = zeroForOne ? slot0Start.protocolFee().getZeroForOneFee() : slot0Start.protocolFee().getOneForZeroFee(); state.amountSpecifiedRemaining = params.amountSpecified; state.amountCalculated = 0; state.sqrtPriceX96 = slot0Start.sqrtPriceX96(); state.tick = slot0Start.tick(); state.feeGrowthGlobalX128 = zeroForOne ? self.feeGrowthGlobal0X128 : self.feeGrowthGlobal1X128; state.liquidity = liquidityStart; // if the beforeSwap hook returned a valid fee override, use that as the LP fee, otherwise load from storage { uint24 lpFee = params.lpFeeOverride.isOverride() ? params.lpFeeOverride.removeOverrideFlagAndValidate() : slot0Start.lpFee(); swapFee = protocolFee == 0 ? lpFee : uint24(protocolFee).calculateSwapFee(lpFee); } bool exactInput = params.amountSpecified < 0; if (!exactInput && (swapFee == LPFeeLibrary.MAX_LP_FEE)) { InvalidFeeForExactOut.selector.revertWith(); } if (params.amountSpecified == 0) return (BalanceDeltaLibrary.ZERO_DELTA, 0, swapFee, state); if (zeroForOne) { if (params.sqrtPriceLimitX96 >= slot0Start.sqrtPriceX96()) { PriceLimitAlreadyExceeded.selector.revertWith(slot0Start.sqrtPriceX96(), params.sqrtPriceLimitX96); } if (params.sqrtPriceLimitX96 <= TickMath.MIN_SQRT_PRICE) { PriceLimitOutOfBounds.selector.revertWith(params.sqrtPriceLimitX96); } } else { if (params.sqrtPriceLimitX96 <= slot0Start.sqrtPriceX96()) { PriceLimitAlreadyExceeded.selector.revertWith(slot0Start.sqrtPriceX96(), params.sqrtPriceLimitX96); } if (params.sqrtPriceLimitX96 >= TickMath.MAX_SQRT_PRICE) { PriceLimitOutOfBounds.selector.revertWith(params.sqrtPriceLimitX96); } } StepComputations memory step; // continue swapping as long as we haven't used the entire input/output and haven't reached the price limit while (!(state.amountSpecifiedRemaining == 0 || state.sqrtPriceX96 == params.sqrtPriceLimitX96)) { step.sqrtPriceStartX96 = state.sqrtPriceX96; (step.tickNext, step.initialized) = self.tickBitmap.nextInitializedTickWithinOneWord(state.tick, params.tickSpacing, zeroForOne); // ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds if (step.tickNext <= TickMath.MIN_TICK) { step.tickNext = TickMath.MIN_TICK; } if (step.tickNext >= TickMath.MAX_TICK) { step.tickNext = TickMath.MAX_TICK; } // get the price for the next tick step.sqrtPriceNextX96 = TickMath.getSqrtPriceAtTick(step.tickNext); // compute values to swap to the target tick, price limit, or point where input/output amount is exhausted (state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath.computeSwapStep( state.sqrtPriceX96, SwapMath.getSqrtPriceTarget(zeroForOne, step.sqrtPriceNextX96, params.sqrtPriceLimitX96), state.liquidity, state.amountSpecifiedRemaining, swapFee ); if (!exactInput) { unchecked { state.amountSpecifiedRemaining -= step.amountOut.toInt256(); } state.amountCalculated = state.amountCalculated - (step.amountIn + step.feeAmount).toInt256(); } else { // safe because we test that amountSpecified > amountIn + feeAmount in SwapMath unchecked { state.amountSpecifiedRemaining += (step.amountIn + step.feeAmount).toInt256(); } state.amountCalculated = state.amountCalculated + step.amountOut.toInt256(); } // if the protocol fee is on, calculate how much is owed, decrement feeAmount, and increment protocolFee if (protocolFee > 0) { unchecked { // step.amountIn does not include the swap fee, as it's already been taken from it, // so add it back to get the total amountIn and use that to calculate the amount of fees owed to the protocol uint256 delta = (step.amountIn + step.feeAmount) * protocolFee / ProtocolFeeLibrary.PIPS_DENOMINATOR; // subtract it from the total fee and add it to the protocol fee step.feeAmount -= delta; feeForProtocol += delta; } } // update global fee tracker if (state.liquidity > 0) { unchecked { state.feeGrowthGlobalX128 += FullMath.mulDiv(step.feeAmount, FixedPoint128.Q128, state.liquidity); } } // shift tick if we reached the next price if (state.sqrtPriceX96 == step.sqrtPriceNextX96) { // if the tick is initialized, run the tick transition if (step.initialized) { (uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = zeroForOne ? (state.feeGrowthGlobalX128, self.feeGrowthGlobal1X128) : (self.feeGrowthGlobal0X128, state.feeGrowthGlobalX128); int128 liquidityNet = Pool.crossTick(self, step.tickNext, feeGrowthGlobal0X128, feeGrowthGlobal1X128); // if we're moving leftward, we interpret liquidityNet as the opposite sign // safe because liquidityNet cannot be type(int128).min unchecked { if (zeroForOne) liquidityNet = -liquidityNet; } state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet); } // Equivalent to `state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;` unchecked { // cannot cast a bool to an int24 in Solidity int24 _zeroForOne; assembly { _zeroForOne := zeroForOne } state.tick = step.tickNext - _zeroForOne; } } else if (state.sqrtPriceX96 != step.sqrtPriceStartX96) { // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved state.tick = TickMath.getTickAtSqrtPrice(state.sqrtPriceX96); } } self.slot0 = slot0Start.setTick(state.tick).setSqrtPriceX96(state.sqrtPriceX96); // update liquidity if it changed if (liquidityStart != state.liquidity) self.liquidity = state.liquidity; // update fee growth global if (!zeroForOne) { self.feeGrowthGlobal1X128 = state.feeGrowthGlobalX128; } else { self.feeGrowthGlobal0X128 = state.feeGrowthGlobalX128; } unchecked { if (zeroForOne != exactInput) { result = toBalanceDelta( state.amountCalculated.toInt128(), (params.amountSpecified - state.amountSpecifiedRemaining).toInt128() ); } else { result = toBalanceDelta( (params.amountSpecified - state.amountSpecifiedRemaining).toInt128(), state.amountCalculated.toInt128() ); } } } /// @notice Donates the given amount of currency0 and currency1 to the pool function donate(State storage state, uint256 amount0, uint256 amount1) internal returns (BalanceDelta delta) { uint128 liquidity = state.liquidity; if (liquidity == 0) NoLiquidityToReceiveFees.selector.revertWith(); unchecked { // negation safe as amount0 and amount1 are always positive delta = toBalanceDelta(-(amount0.toInt128()), -(amount1.toInt128())); if (amount0 > 0) { state.feeGrowthGlobal0X128 += FullMath.mulDiv(amount0, FixedPoint128.Q128, liquidity); } if (amount1 > 0) { state.feeGrowthGlobal1X128 += FullMath.mulDiv(amount1, FixedPoint128.Q128, liquidity); } } } /// @notice Retrieves fee growth data /// @param self The Pool state struct /// @param tickLower The lower tick boundary of the position /// @param tickUpper The upper tick boundary of the position /// @return feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries /// @return feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries function getFeeGrowthInside(State storage self, int24 tickLower, int24 tickUpper) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) { TickInfo storage lower = self.ticks[tickLower]; TickInfo storage upper = self.ticks[tickUpper]; int24 tickCurrent = self.slot0.tick(); unchecked { if (tickCurrent < tickLower) { feeGrowthInside0X128 = lower.feeGrowthOutside0X128 - upper.feeGrowthOutside0X128; feeGrowthInside1X128 = lower.feeGrowthOutside1X128 - upper.feeGrowthOutside1X128; } else if (tickCurrent >= tickUpper) { feeGrowthInside0X128 = upper.feeGrowthOutside0X128 - lower.feeGrowthOutside0X128; feeGrowthInside1X128 = upper.feeGrowthOutside1X128 - lower.feeGrowthOutside1X128; } else { feeGrowthInside0X128 = self.feeGrowthGlobal0X128 - lower.feeGrowthOutside0X128 - upper.feeGrowthOutside0X128; feeGrowthInside1X128 = self.feeGrowthGlobal1X128 - lower.feeGrowthOutside1X128 - upper.feeGrowthOutside1X128; } } } /// @notice Updates a tick and returns true if the tick was flipped from initialized to uninitialized, or vice versa /// @param self The mapping containing all tick information for initialized ticks /// @param tick The tick that will be updated /// @param liquidityDelta A new amount of liquidity to be added (subtracted) when tick is crossed from left to right (right to left) /// @param upper true for updating a position's upper tick, or false for updating a position's lower tick /// @return flipped Whether the tick was flipped from initialized to uninitialized, or vice versa /// @return liquidityGrossAfter The total amount of liquidity for all positions that references the tick after the update function updateTick(State storage self, int24 tick, int128 liquidityDelta, bool upper) internal returns (bool flipped, uint128 liquidityGrossAfter) { TickInfo storage info = self.ticks[tick]; uint128 liquidityGrossBefore; int128 liquidityNetBefore; assembly { // load first slot of info which contains liquidityGross and liquidityNet packed // where the top 128 bits are liquidityNet and the bottom 128 bits are liquidityGross let liquidity := sload(info.slot) // slice off top 128 bits of liquidity (liquidityNet) to get just liquidityGross liquidityGrossBefore := shr(128, shl(128, liquidity)) // signed shift right 128 bits to get just liquidityNet liquidityNetBefore := sar(128, liquidity) } liquidityGrossAfter = LiquidityMath.addDelta(liquidityGrossBefore, liquidityDelta); flipped = (liquidityGrossAfter == 0) != (liquidityGrossBefore == 0); if (liquidityGrossBefore == 0) { // by convention, we assume that all growth before a tick was initialized happened _below_ the tick if (tick <= self.slot0.tick()) { info.feeGrowthOutside0X128 = self.feeGrowthGlobal0X128; info.feeGrowthOutside1X128 = self.feeGrowthGlobal1X128; } } // when the lower (upper) tick is crossed left to right (right to left), liquidity must be added (removed) int128 liquidityNet = upper ? liquidityNetBefore - liquidityDelta : liquidityNetBefore + liquidityDelta; assembly { // liquidityGrossAfter and liquidityNet are packed in the first slot of `info` // So we can store them with a single sstore by packing them ourselves first sstore( info.slot, // bitwise OR to pack liquidityGrossAfter and liquidityNet or( // liquidityGross is in the low bits, upper bits are already 0 liquidityGrossAfter, // shift liquidityNet to take the upper bits and lower bits get filled with 0 shl(128, liquidityNet) ) ) } } /// @notice Derives max liquidity per tick from given tick spacing /// @dev Executed within the pool constructor /// @param tickSpacing The amount of required tick separation, realized in multiples of `tickSpacing` /// e.g., a tickSpacing of 3 requires ticks to be initialized every 3rd tick i.e., ..., -6, -3, 0, 3, 6, ... /// @return result The max liquidity per tick function tickSpacingToMaxLiquidityPerTick(int24 tickSpacing) internal pure returns (uint128 result) { // Equivalent to: // int24 minTick = (TickMath.MIN_TICK / tickSpacing) * tickSpacing; // int24 maxTick = (TickMath.MAX_TICK / tickSpacing) * tickSpacing; // uint24 numTicks = uint24((maxTick - minTick) / tickSpacing) + 1; // return type(uint128).max / numTicks; int24 MAX_TICK = TickMath.MAX_TICK; int24 MIN_TICK = TickMath.MIN_TICK; // tick spacing will never be 0 since TickMath.MIN_TICK_SPACING is 1 assembly { let minTick := mul(sdiv(MIN_TICK, tickSpacing), tickSpacing) let maxTick := mul(sdiv(MAX_TICK, tickSpacing), tickSpacing) let numTicks := add(sdiv(sub(maxTick, minTick), tickSpacing), 1) result := div(sub(shl(128, 1), 1), numTicks) } } /// @notice Reverts if the given pool has not been initialized function checkPoolInitialized(State storage self) internal view { if (self.slot0.sqrtPriceX96() == 0) PoolNotInitialized.selector.revertWith(); } /// @notice Clears tick data /// @param self The mapping containing all initialized tick information for initialized ticks /// @param tick The tick that will be cleared function clearTick(State storage self, int24 tick) internal { delete self.ticks[tick]; } /// @notice Transitions to next tick as needed by price movement /// @param self The Pool state struct /// @param tick The destination tick of the transition /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0 /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1 /// @return liquidityNet The amount of liquidity added (subtracted) when tick is crossed from left to right (right to left) function crossTick(State storage self, int24 tick, uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) internal returns (int128 liquidityNet) { unchecked { TickInfo storage info = self.ticks[tick]; info.feeGrowthOutside0X128 = feeGrowthGlobal0X128 - info.feeGrowthOutside0X128; info.feeGrowthOutside1X128 = feeGrowthGlobal1X128 - info.feeGrowthOutside1X128; liquidityNet = info.liquidityNet; } } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.20; import {FullMath} from "./FullMath.sol"; import {FixedPoint128} from "./FixedPoint128.sol"; import {LiquidityMath} from "./LiquidityMath.sol"; import {CustomRevert} from "./CustomRevert.sol"; /// @title Position /// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary /// @dev Positions store additional state for tracking fees owed to the position library Position { using CustomRevert for bytes4; /// @notice Cannot update a position with no liquidity error CannotUpdateEmptyPosition(); // info stored for each user's position struct Info { // the amount of liquidity owned by this position uint128 liquidity; // fee growth per unit of liquidity as of the last update to liquidity or fees owed uint256 feeGrowthInside0LastX128; uint256 feeGrowthInside1LastX128; } /// @notice Returns the Info struct of a position, given an owner and position boundaries /// @param self The mapping containing all user positions /// @param owner The address of the position owner /// @param tickLower The lower tick boundary of the position /// @param tickUpper The upper tick boundary of the position /// @param salt A unique value to differentiate between multiple positions in the same range /// @return position The position info struct of the given owners' position function get(mapping(bytes32 => Info) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt) internal view returns (Info storage position) { // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt)) bytes32 positionKey; assembly ("memory-safe") { mstore(0x26, salt) // [0x26, 0x46) mstore(0x06, tickUpper) // [0x23, 0x26) mstore(0x03, tickLower) // [0x20, 0x23) mstore(0, owner) // [0x0c, 0x20) positionKey := keccak256(0x0c, 0x3a) // len is 58 bytes mstore(0x26, 0) // rewrite 0x26 to 0 } position = self[positionKey]; } /// @notice Credits accumulated fees to a user's position /// @param self The individual position to update /// @param liquidityDelta The change in pool liquidity as a result of the position update /// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries /// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries /// @return feesOwed0 The amount of currency0 owed to the position owner /// @return feesOwed1 The amount of currency1 owed to the position owner function update( Info storage self, int128 liquidityDelta, uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128 ) internal returns (uint256 feesOwed0, uint256 feesOwed1) { uint128 liquidity = self.liquidity; if (liquidityDelta == 0) { // disallow pokes for 0 liquidity positions if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith(); } else { self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta); } // calculate accumulated fees. overflow in the subtraction of fee growth is expected unchecked { feesOwed0 = FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128); feesOwed1 = FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128); } // update the position self.feeGrowthInside0LastX128 = feeGrowthInside0X128; self.feeGrowthInside1LastX128 = feeGrowthInside1X128; } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; library ProtocolFeeLibrary { // Max protocol fee is 0.1% (1000 pips) uint16 public constant MAX_PROTOCOL_FEE = 1000; // Thresholds used for optimized bounds checks on protocol fees uint24 internal constant FEE_0_THRESHOLD = 1001; uint24 internal constant FEE_1_THRESHOLD = 1001 << 12; // the protocol fee is represented in hundredths of a bip uint256 internal constant PIPS_DENOMINATOR = 1_000_000; function getZeroForOneFee(uint24 self) internal pure returns (uint16) { return uint16(self & 0xfff); } function getOneForZeroFee(uint24 self) internal pure returns (uint16) { return uint16(self >> 12); } function isValidProtocolFee(uint24 self) internal pure returns (bool valid) { // Equivalent to: getZeroForOneFee(self) <= MAX_PROTOCOL_FEE && getOneForZeroFee(self) <= MAX_PROTOCOL_FEE assembly { let isZeroForOneFeeOk := lt(and(self, 0xfff), FEE_0_THRESHOLD) let isOneForZeroFeeOk := lt(self, FEE_1_THRESHOLD) valid := and(isZeroForOneFeeOk, isOneForZeroFeeOk) } } // The protocol fee is taken from the input amount first and then the LP fee is taken from the remaining // The swap fee is capped at 100% // Equivalent to protocolFee + lpFee(1_000_000 - protocolFee) / 1_000_000 function calculateSwapFee(uint24 self, uint24 lpFee) internal pure returns (uint24 swapFee) { // protocolFee + lpFee - (protocolFee * lpFee / 1_000_000). Div rounds up to favor LPs over the protocol. assembly { let numerator := mul(self, lpFee) let divRoundingUp := add(div(numerator, PIPS_DENOMINATOR), gt(mod(numerator, PIPS_DENOMINATOR), 0)) swapFee := sub(add(self, lpFee), divRoundingUp) } } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.20; import {Currency} from "../types/Currency.sol"; import {CustomRevert} from "./CustomRevert.sol"; library Reserves { using CustomRevert for bytes4; /// bytes32(uint256(keccak256("ReservesOf")) - 1) bytes32 constant RESERVES_OF_SLOT = 0x1e0745a7db1623981f0b2a5d4232364c00787266eb75ad546f190e6cebe9bd95; /// @notice The transient reserves for pools with no balance is set to the max as a sentinel to track that it has been synced. uint256 public constant ZERO_BALANCE = type(uint256).max; /// @notice Thrown when someone has not called sync before calling settle for the first time. error ReservesMustBeSynced(); function setReserves(Currency currency, uint256 value) internal { if (value == 0) value = ZERO_BALANCE; bytes32 key = _getKey(currency); assembly { tstore(key, value) } } function getReserves(Currency currency) internal view returns (uint256 value) { bytes32 key = _getKey(currency); assembly { value := tload(key) } if (value == 0) ReservesMustBeSynced.selector.revertWith(); if (value == ZERO_BALANCE) value = 0; } function _getKey(Currency currency) private pure returns (bytes32 key) { assembly ("memory-safe") { mstore(0, RESERVES_OF_SLOT) mstore(32, currency) key := keccak256(0, 64) } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { error SafeCastOverflow(); function _revertOverflow() private pure { assembly ("memory-safe") { // Store the function selector of `SafeCastOverflow()`. mstore(0x00, 0x93dafdf1) // Revert with (offset, size). revert(0x1c, 0x04) } } /// @notice Cast a uint256 to a uint160, revert on overflow /// @param x The uint256 to be downcasted /// @return The downcasted integer, now type uint160 function toUint160(uint256 x) internal pure returns (uint160) { if (x >= 1 << 160) _revertOverflow(); return uint160(x); } /// @notice Cast a uint256 to a uint128, revert on overflow /// @param x The uint256 to be downcasted /// @return The downcasted integer, now type uint128 function toUint128(uint256 x) internal pure returns (uint128) { if (x >= 1 << 128) _revertOverflow(); return uint128(x); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param x The int256 to be downcasted /// @return The downcasted integer, now type int128 function toInt128(int256 x) internal pure returns (int128) { unchecked { if (((1 << 127) + uint256(x)) >> 128 == uint256(0)) return int128(x); _revertOverflow(); } } /// @notice Cast a uint256 to a int256, revert on overflow /// @param x The uint256 to be casted /// @return The casted integer, now type int256 function toInt256(uint256 x) internal pure returns (int256) { if (int256(x) >= 0) return int256(x); _revertOverflow(); } /// @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) _revertOverflow(); return int128(int256(x)); } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; import {SafeCast} from "./SafeCast.sol"; import {FullMath} from "./FullMath.sol"; import {UnsafeMath} from "./UnsafeMath.sol"; import {FixedPoint96} from "./FixedPoint96.sol"; /// @title Functions based on Q64.96 sqrt price and liquidity /// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas library SqrtPriceMath { using SafeCast for uint256; error InvalidPriceOrLiquidity(); error InvalidPrice(); error NotEnoughLiquidity(); error PriceOverflow(); /// @notice Gets the next sqrt price given a delta of currency0 /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the /// price less in order to not send too much output. /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96), /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount). /// @param sqrtPX96 The starting price, i.e. before accounting for the currency0 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of currency0 to add or remove from virtual reserves /// @param add Whether to add or remove the amount of currency0 /// @return The price after adding or removing amount, depending on add function getNextSqrtPriceFromAmount0RoundingUp(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add) internal pure returns (uint160) { // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price if (amount == 0) return sqrtPX96; uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; if (add) { unchecked { uint256 product = amount * sqrtPX96; if (product / amount == sqrtPX96) { uint256 denominator = numerator1 + product; if (denominator >= numerator1) { // always fits in 160 bits return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator)); } } } // denominator is checked for overflow return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96) + amount)); } else { unchecked { uint256 product = amount * sqrtPX96; // if the product overflows, we know the denominator underflows // in addition, we must check that the denominator does not underflow // equivalent: if (product / amount != sqrtPX96 || numerator1 <= product) revert PriceOverflow(); assembly ("memory-safe") { if iszero(and(eq(div(product, amount), sqrtPX96), gt(numerator1, product))) { mstore(0, 0xf5c787f1) // selector for PriceOverflow() revert(0x1c, 0x04) } } uint256 denominator = numerator1 - product; return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160(); } } } /// @notice Gets the next sqrt price given a delta of currency1 /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the /// price less in order to not send too much output. /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity /// @param sqrtPX96 The starting price, i.e., before accounting for the currency1 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of currency1 to add, or remove, from virtual reserves /// @param add Whether to add, or remove, the amount of currency1 /// @return The price after adding or removing `amount` function getNextSqrtPriceFromAmount1RoundingDown(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add) internal pure returns (uint160) { // if we're adding (subtracting), rounding down requires rounding the quotient down (up) // in both cases, avoid a mulDiv for most inputs if (add) { uint256 quotient = ( amount <= type(uint160).max ? (amount << FixedPoint96.RESOLUTION) / liquidity : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity) ); return (uint256(sqrtPX96) + quotient).toUint160(); } else { uint256 quotient = ( amount <= type(uint160).max ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity) : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity) ); // equivalent: if (sqrtPX96 <= quotient) revert NotEnoughLiquidity(); assembly ("memory-safe") { if iszero(gt(sqrtPX96, quotient)) { mstore(0, 0x4323a555) // selector for NotEnoughLiquidity() revert(0x1c, 0x04) } } // always fits 160 bits unchecked { return uint160(sqrtPX96 - quotient); } } } /// @notice Gets the next sqrt price given an input amount of currency0 or currency1 /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount /// @param liquidity The amount of usable liquidity /// @param amountIn How much of currency0, or currency1, is being swapped in /// @param zeroForOne Whether the amount in is currency0 or currency1 /// @return sqrtQX96 The price after adding the input amount to currency0 or currency1 function getNextSqrtPriceFromInput(uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne) internal pure returns (uint160 sqrtQX96) { // equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity(); assembly ("memory-safe") { if or(iszero(sqrtPX96), iszero(liquidity)) { mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity() revert(0x1c, 0x04) } } // round to make sure that we don't pass the target price return zeroForOne ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true) : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true); } /// @notice Gets the next sqrt price given an output amount of currency0 or currency1 /// @dev Throws if price or liquidity are 0 or the next price is out of bounds /// @param sqrtPX96 The starting price before accounting for the output amount /// @param liquidity The amount of usable liquidity /// @param amountOut How much of currency0, or currency1, is being swapped out /// @param zeroForOne Whether the amount out is currency1 or currency0 /// @return sqrtQX96 The price after removing the output amount of currency0 or currency1 function getNextSqrtPriceFromOutput(uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne) internal pure returns (uint160 sqrtQX96) { // equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity(); assembly ("memory-safe") { if or(iszero(sqrtPX96), iszero(liquidity)) { mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity() revert(0x1c, 0x04) } } // round to make sure that we pass the target price return zeroForOne ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false); } /// @notice Gets the amount0 delta between two prices /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper), /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower)) /// @param sqrtPriceAX96 A sqrt price /// @param sqrtPriceBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up or down /// @return amount0 Amount of currency0 required to cover a position of size liquidity between the two passed prices function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp) internal pure returns (uint256 amount0) { unchecked { if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96); // equivalent: if (sqrtPriceAX96 == 0) revert InvalidPrice(); assembly ("memory-safe") { if iszero(sqrtPriceAX96) { mstore(0, 0x00bfc921) // selector for InvalidPrice() revert(0x1c, 0x04) } } uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; uint256 numerator2 = sqrtPriceBX96 - sqrtPriceAX96; return roundUp ? UnsafeMath.divRoundingUp(FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtPriceBX96), sqrtPriceAX96) : FullMath.mulDiv(numerator1, numerator2, sqrtPriceBX96) / sqrtPriceAX96; } } /// @notice Equivalent to: `a >= b ? a - b : b - a` function absDiff(uint160 a, uint160 b) internal pure returns (uint256 res) { assembly { let diff := sub(a, b) // mask = 0 if a >= b else -1 (all 1s) let mask := sar(255, diff) // if a >= b, res = a - b = 0 ^ (a - b) // if a < b, res = b - a = ~~(b - a) = ~(-(b - a) - 1) = ~(a - b - 1) = (-1) ^ (a - b - 1) // either way, res = mask ^ (a - b + mask) res := xor(mask, add(mask, diff)) } } /// @notice Gets the amount1 delta between two prices /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower)) /// @param sqrtPriceAX96 A sqrt price /// @param sqrtPriceBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up, or down /// @return amount1 Amount of currency1 required to cover a position of size liquidity between the two passed prices function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp) internal pure returns (uint256 amount1) { uint256 numerator = absDiff(sqrtPriceAX96, sqrtPriceBX96); uint256 denominator = FixedPoint96.Q96; uint256 _liquidity; assembly { // avoid implicit upcasting _liquidity := liquidity } /** * Equivalent to: * amount1 = roundUp * ? FullMath.mulDivRoundingUp(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96) * : FullMath.mulDiv(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96); * Cannot overflow because `type(uint128).max * type(uint160).max >> 96 < (1 << 192)`. */ amount1 = FullMath.mulDiv(_liquidity, numerator, denominator); assembly { amount1 := add(amount1, and(gt(mulmod(_liquidity, numerator, denominator), 0), roundUp)) } } /// @notice Helper that gets signed currency0 delta /// @param sqrtPriceAX96 A sqrt price /// @param sqrtPriceBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount0 delta /// @return amount0 Amount of currency0 corresponding to the passed liquidityDelta between the two prices function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity) internal pure returns (int256 amount0) { unchecked { return liquidity < 0 ? getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256() : -getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256(); } } /// @notice Helper that gets signed currency1 delta /// @param sqrtPriceAX96 A sqrt price /// @param sqrtPriceBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount1 delta /// @return amount1 Amount of currency1 corresponding to the passed liquidityDelta between the two prices function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity) internal pure returns (int256 amount1) { unchecked { return liquidity < 0 ? getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256() : -getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256(); } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; import {FullMath} from "./FullMath.sol"; import {SqrtPriceMath} from "./SqrtPriceMath.sol"; /// @title Computes the result of a swap within ticks /// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick. library SwapMath { uint256 internal constant MAX_FEE_PIPS = 1e6; /// @notice Computes the sqrt price target for the next swap step /// @param zeroForOne The direction of the swap, true for currency0 to currency1, false for currency1 to currency0 /// @param sqrtPriceNextX96 The Q64.96 sqrt price for the next initialized tick /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value /// after the swap. If one for zero, the price cannot be greater than this value after the swap /// @return sqrtPriceTargetX96 The price target for the next swap step function getSqrtPriceTarget(bool zeroForOne, uint160 sqrtPriceNextX96, uint160 sqrtPriceLimitX96) internal pure returns (uint160 sqrtPriceTargetX96) { assembly { // a flag to toggle between sqrtPriceNextX96 and sqrtPriceLimitX96 // when zeroForOne == true, nextOrLimit reduces to sqrtPriceNextX96 >= sqrtPriceLimitX96 // sqrtPriceTargetX96 = max(sqrtPriceNextX96, sqrtPriceLimitX96) // when zeroForOne == false, nextOrLimit reduces to sqrtPriceNextX96 < sqrtPriceLimitX96 // sqrtPriceTargetX96 = min(sqrtPriceNextX96, sqrtPriceLimitX96) let nextOrLimit := xor(lt(sqrtPriceNextX96, sqrtPriceLimitX96), zeroForOne) let symDiff := xor(sqrtPriceNextX96, sqrtPriceLimitX96) sqrtPriceTargetX96 := xor(sqrtPriceLimitX96, mul(symDiff, nextOrLimit)) } } /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap /// @dev If the swap's amountSpecified is negative, the combined fee and input amount will never exceed the absolute value of the remaining amount. /// @param sqrtPriceCurrentX96 The current sqrt price of the pool /// @param sqrtPriceTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred /// @param liquidity The usable liquidity /// @param amountRemaining How much input or output amount is remaining to be swapped in/out /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip /// @return sqrtPriceNextX96 The price after swapping the amount in/out, not to exceed the price target /// @return amountIn The amount to be swapped in, of either currency0 or currency1, based on the direction of the swap /// @return amountOut The amount to be received, of either currency0 or currency1, based on the direction of the swap /// @return feeAmount The amount of input that will be taken as a fee function computeSwapStep( uint160 sqrtPriceCurrentX96, uint160 sqrtPriceTargetX96, uint128 liquidity, int256 amountRemaining, uint24 feePips ) internal pure returns (uint160 sqrtPriceNextX96, uint256 amountIn, uint256 amountOut, uint256 feeAmount) { unchecked { uint256 _feePips = feePips; // upcast once and cache bool zeroForOne = sqrtPriceCurrentX96 >= sqrtPriceTargetX96; bool exactIn = amountRemaining < 0; if (exactIn) { uint256 amountRemainingLessFee = FullMath.mulDiv(uint256(-amountRemaining), MAX_FEE_PIPS - _feePips, MAX_FEE_PIPS); amountIn = zeroForOne ? SqrtPriceMath.getAmount0Delta(sqrtPriceTargetX96, sqrtPriceCurrentX96, liquidity, true) : SqrtPriceMath.getAmount1Delta(sqrtPriceCurrentX96, sqrtPriceTargetX96, liquidity, true); if (amountRemainingLessFee >= amountIn) { // `amountIn` is capped by the target price sqrtPriceNextX96 = sqrtPriceTargetX96; feeAmount = _feePips == MAX_FEE_PIPS ? amountIn : FullMath.mulDivRoundingUp(amountIn, _feePips, MAX_FEE_PIPS - _feePips); } else { sqrtPriceNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput( sqrtPriceCurrentX96, liquidity, amountRemainingLessFee, zeroForOne ); amountIn = zeroForOne ? SqrtPriceMath.getAmount0Delta(sqrtPriceNextX96, sqrtPriceCurrentX96, liquidity, true) : SqrtPriceMath.getAmount1Delta(sqrtPriceCurrentX96, sqrtPriceNextX96, liquidity, true); // we didn't reach the target, so take the remainder of the maximum input as fee feeAmount = uint256(-amountRemaining) - amountIn; } amountOut = zeroForOne ? SqrtPriceMath.getAmount1Delta(sqrtPriceNextX96, sqrtPriceCurrentX96, liquidity, false) : SqrtPriceMath.getAmount0Delta(sqrtPriceCurrentX96, sqrtPriceNextX96, liquidity, false); } else { amountOut = zeroForOne ? SqrtPriceMath.getAmount1Delta(sqrtPriceTargetX96, sqrtPriceCurrentX96, liquidity, false) : SqrtPriceMath.getAmount0Delta(sqrtPriceCurrentX96, sqrtPriceTargetX96, liquidity, false); if (uint256(amountRemaining) >= amountOut) { // `amountOut` is capped by the target price sqrtPriceNextX96 = sqrtPriceTargetX96; } else { // cap the output amount to not exceed the remaining output amount amountOut = uint256(amountRemaining); sqrtPriceNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(sqrtPriceCurrentX96, liquidity, amountOut, zeroForOne); } amountIn = zeroForOne ? SqrtPriceMath.getAmount0Delta(sqrtPriceNextX96, sqrtPriceCurrentX96, liquidity, true) : SqrtPriceMath.getAmount1Delta(sqrtPriceCurrentX96, sqrtPriceNextX96, liquidity, true); // `feePips` cannot be `MAX_FEE_PIPS` for exact out feeAmount = FullMath.mulDivRoundingUp(amountIn, _feePips, MAX_FEE_PIPS - _feePips); } } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import {BitMath} from "./BitMath.sol"; /// @title Packed tick initialized state library /// @notice Stores a packed mapping of tick index to its initialized state /// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word. library TickBitmap { /// @notice Thrown when the tick is not enumerated by the tick spacing /// @param tick the invalid tick /// @param tickSpacing The tick spacing of the pool error TickMisaligned(int24 tick, int24 tickSpacing); /// @dev round towards negative infinity function compress(int24 tick, int24 tickSpacing) internal pure returns (int24 compressed) { // compressed = tick / tickSpacing; // if (tick < 0 && tick % tickSpacing != 0) compressed--; assembly { compressed := sub( sdiv(tick, tickSpacing), // if (tick < 0 && tick % tickSpacing != 0) then tick % tickSpacing < 0, vice versa slt(smod(tick, tickSpacing), 0) ) } } /// @notice Computes the position in the mapping where the initialized bit for a tick lives /// @param tick The tick for which to compute the position /// @return wordPos The key in the mapping containing the word in which the bit is stored /// @return bitPos The bit position in the word where the flag is stored function position(int24 tick) internal pure returns (int16 wordPos, uint8 bitPos) { assembly { // signed arithmetic shift right wordPos := sar(8, tick) bitPos := and(tick, 0xff) } } /// @notice Flips the initialized state for a given tick from false to true, or vice versa /// @param self The mapping in which to flip the tick /// @param tick The tick to flip /// @param tickSpacing The spacing between usable ticks function flipTick(mapping(int16 => uint256) storage self, int24 tick, int24 tickSpacing) internal { // Equivalent to the following Solidity: // if (tick % tickSpacing != 0) revert TickMisaligned(tick, tickSpacing); // (int16 wordPos, uint8 bitPos) = position(tick / tickSpacing); // uint256 mask = 1 << bitPos; // self[wordPos] ^= mask; assembly ("memory-safe") { // ensure that the tick is spaced if smod(tick, tickSpacing) { mstore(0, 0xd4d8f3e6) // selector for TickMisaligned(int24,int24) mstore(0x20, tick) mstore(0x40, tickSpacing) revert(0x1c, 0x44) } tick := sdiv(tick, tickSpacing) // calculate the storage slot corresponding to the tick // wordPos = tick >> 8 mstore(0, sar(8, tick)) mstore(0x20, self.slot) // the slot of self[wordPos] is keccak256(abi.encode(wordPos, self.slot)) let slot := keccak256(0, 0x40) // mask = 1 << bitPos = 1 << (tick % 256) // self[wordPos] ^= mask sstore(slot, xor(sload(slot), shl(and(tick, 0xff), 1))) } } /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either /// to the left (less than or equal to) or right (greater than) of the given tick /// @param self The mapping in which to compute the next initialized tick /// @param tick The starting tick /// @param tickSpacing The spacing between usable ticks /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick) /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks function nextInitializedTickWithinOneWord( mapping(int16 => uint256) storage self, int24 tick, int24 tickSpacing, bool lte ) internal view returns (int24 next, bool initialized) { unchecked { int24 compressed = compress(tick, tickSpacing); if (lte) { (int16 wordPos, uint8 bitPos) = position(compressed); // all the 1s at or to the right of the current bitPos uint256 mask = (1 << bitPos) - 1 + (1 << bitPos); uint256 masked = self[wordPos] & mask; // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word initialized = masked != 0; // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick next = initialized ? (compressed - int24(uint24(bitPos - BitMath.mostSignificantBit(masked)))) * tickSpacing : (compressed - int24(uint24(bitPos))) * tickSpacing; } else { // start from the word of the next tick, since the current tick state doesn't matter (int16 wordPos, uint8 bitPos) = position(++compressed); // all the 1s at or to the left of the bitPos uint256 mask = ~((1 << bitPos) - 1); uint256 masked = self[wordPos] & mask; // if there are no initialized ticks to the left of the current tick, return leftmost in the word initialized = masked != 0; // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick next = initialized ? (compressed + int24(uint24(BitMath.leastSignificantBit(masked) - bitPos))) * tickSpacing : (compressed + int24(uint24(type(uint8).max - bitPos))) * tickSpacing; } } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @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 { /// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK error InvalidTick(); /// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK error InvalidSqrtPrice(); /// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128 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 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 { // 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)) } // Equivalent: if (absTick > MAX_TICK) revert InvalidTick(); assembly ("memory-safe") { if gt(absTick, MAX_TICK) { // store 4-byte selector of "InvalidTick()" at memory [0x1c, 0x20) mstore(0, 0xce8ef7fc) revert(0x1c, 0x04) } } // 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 { 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 { // 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 getPriceAtTick(tick) <= price /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getPriceAtTick 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 price is less than or equal to the input price 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 assembly ("memory-safe") { // 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 gt(sub(sqrtPriceX96, MIN_SQRT_PRICE), MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) { // store 4-byte selector of "InvalidSqrtPrice()" at memory [0x1c, 0x20) mstore(0, 0x31efafe8) revert(0x1c, 0x04) } } uint256 price = uint256(sqrtPriceX96) << 32; uint256 r = price; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = price >> (msb - 127); else r = price << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { 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; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @title Math functions that do not check inputs or outputs /// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks library UnsafeMath { /// @notice Returns ceil(x / y) /// @dev division by 0 has unspecified behavior, and must be checked externally /// @param x The dividend /// @param y The divisor /// @return z The quotient, ceil(x / y) function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) { unchecked { assembly { z := add(div(x, y), gt(mod(x, y), 0)) } } } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.20; import {CustomRevert} from "./libraries/CustomRevert.sol"; /// @title Prevents delegatecall to a contract /// @notice Base contract that provides a modifier for preventing delegatecall to methods in a child contract abstract contract NoDelegateCall { using CustomRevert for bytes4; error DelegateCallNotAllowed(); /// @dev The original address of this contract address private immutable original; constructor() { // Immutables are computed in the init code of the contract, and then inlined into the deployed bytecode. // In other words, this variable won't change when it's checked at runtime. original = address(this); } /// @dev Private method is used instead of inlining into modifier because modifiers are copied into each method, /// and the use of immutable means the address bytes are copied in every place the modifier is used. function checkNotDelegateCall() private view { if (address(this) != original) DelegateCallNotAllowed.selector.revertWith(); } /// @notice Prevents delegatecall into the modified method modifier noDelegateCall() { checkNotDelegateCall(); _; } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; import {Hooks} from "./libraries/Hooks.sol"; import {Pool} from "./libraries/Pool.sol"; import {SafeCast} from "./libraries/SafeCast.sol"; import {Position} from "./libraries/Position.sol"; import {LPFeeLibrary} from "./libraries/LPFeeLibrary.sol"; import {Currency, CurrencyLibrary} from "./types/Currency.sol"; import {PoolKey} from "./types/PoolKey.sol"; import {TickMath} from "./libraries/TickMath.sol"; import {NoDelegateCall} from "./NoDelegateCall.sol"; import {IHooks} from "./interfaces/IHooks.sol"; import {IPoolManager} from "./interfaces/IPoolManager.sol"; import {IUnlockCallback} from "./interfaces/callback/IUnlockCallback.sol"; import {ProtocolFees} from "./ProtocolFees.sol"; import {ERC6909Claims} from "./ERC6909Claims.sol"; import {PoolId, PoolIdLibrary} from "./types/PoolId.sol"; import {BalanceDelta, BalanceDeltaLibrary, toBalanceDelta} from "./types/BalanceDelta.sol"; import {BeforeSwapDelta} from "./types/BeforeSwapDelta.sol"; import {Lock} from "./libraries/Lock.sol"; import {CurrencyDelta} from "./libraries/CurrencyDelta.sol"; import {NonZeroDeltaCount} from "./libraries/NonZeroDeltaCount.sol"; import {Reserves} from "./libraries/Reserves.sol"; import {Extsload} from "./Extsload.sol"; import {Exttload} from "./Exttload.sol"; import {CustomRevert} from "./libraries/CustomRevert.sol"; // 4 // 44 // 444 // 444 4444 // 4444 4444 4444 // 4444 4444444 4444 4 // 4444 44444444 4444 4 // 44444 4444444 4444444444444444 444444 // 4 44444 44444444 444444444444444444444 4444 // 4 44444 4444444 4444444444444444444444 44444 // 4 444444 4444444 44444444444444444444444 44 4 // 44 44444 444444 444444444444444444444 4 4 // 44 44444 44444 4444444444444444444 4 44 // 44 4444 44 444444444444444 444 // 444 4444 4444444 // 4444444444444 44 4 // 44444444444 444444 444444444 44 // 444444 4444 4444 4444444444 44 // 4444 44 44 4 44444444444 // 44444 444444444 444444444444 4444 // 44444 44444444 4444 44444444 444444 // 44444 4444 444444444 44444444 // 44444 4444 44444444 4444444444 // 44444 4444 444444444 444444444444 // 44444 4444 44444444 444444444444 // 4444444 4444 44444444 4444444 // 4444444 44444 44444444 4444444 // 44444444 44444444444444444444444444444 4444 // 4444444444 44444444444444444444444444444 444 // 444444444444 444444444444444444444444444444 444 444 // 44444444444444 444444444 44444 // 44444 44444444444 444 44444444 444444 // 44444 4444444444 4444444444 444444 44444444 444444444444 // 444444444444444 4444 444444 4444444 44444444 444444444444 // 444444444444444 444 444444 444444 44444444 44444444444 // 4444444444444 4444 444444 4444 4444444444 // 444444444444 4 44444 4444 444444444 // 44444444444 444444 444 44444444 // 44444444 444444 4444 4444444 // 44444 444 44444 // 44444 444 4 4444 // 44444 444 44 444 // 44444 444 4444 // 444444 44444 444 // 444444444 444 // 44444 444 // 444 /// @title PoolManager /// @notice Holds the state for all pools contract PoolManager is IPoolManager, ProtocolFees, NoDelegateCall, ERC6909Claims, Extsload, Exttload { using PoolIdLibrary for PoolKey; using SafeCast for *; using Pool for *; using Hooks for IHooks; using Position for mapping(bytes32 => Position.Info); using CurrencyDelta for Currency; using LPFeeLibrary for uint24; using Reserves for Currency; using CustomRevert for bytes4; /// @inheritdoc IPoolManager int24 public constant MAX_TICK_SPACING = TickMath.MAX_TICK_SPACING; /// @inheritdoc IPoolManager int24 public constant MIN_TICK_SPACING = TickMath.MIN_TICK_SPACING; mapping(PoolId id => Pool.State) internal _pools; constructor(uint256 controllerGasLimit) ProtocolFees(controllerGasLimit) {} /// @notice This will revert if the contract is locked modifier onlyWhenUnlocked() { if (!Lock.isUnlocked()) ManagerLocked.selector.revertWith(); _; } /// @inheritdoc IPoolManager function unlock(bytes calldata data) external override returns (bytes memory result) { if (Lock.isUnlocked()) AlreadyUnlocked.selector.revertWith(); Lock.unlock(); // the caller does everything in this callback, including paying what they owe via calls to settle result = IUnlockCallback(msg.sender).unlockCallback(data); if (NonZeroDeltaCount.read() != 0) CurrencyNotSettled.selector.revertWith(); Lock.lock(); } /// @inheritdoc IPoolManager function initialize(PoolKey memory key, uint160 sqrtPriceX96, bytes calldata hookData) external override noDelegateCall returns (int24 tick) { // see TickBitmap.sol for overflow conditions that can arise from tick spacing being too large if (key.tickSpacing > MAX_TICK_SPACING) TickSpacingTooLarge.selector.revertWith(); if (key.tickSpacing < MIN_TICK_SPACING) TickSpacingTooSmall.selector.revertWith(); if (key.currency0 >= key.currency1) CurrenciesOutOfOrderOrEqual.selector.revertWith(); if (!key.hooks.isValidHookAddress(key.fee)) Hooks.HookAddressNotValid.selector.revertWith(address(key.hooks)); uint24 lpFee = key.fee.getInitialLPFee(); key.hooks.beforeInitialize(key, sqrtPriceX96, hookData); PoolId id = key.toId(); (, uint24 protocolFee) = _fetchProtocolFee(key); tick = _pools[id].initialize(sqrtPriceX96, protocolFee, lpFee); key.hooks.afterInitialize(key, sqrtPriceX96, tick, hookData); // emit all details of a pool key. poolkeys are not saved in storage and must always be provided by the caller // the key's fee may be a static fee or a sentinel to denote a dynamic fee. emit Initialize(id, key.currency0, key.currency1, key.fee, key.tickSpacing, key.hooks); } /// @inheritdoc IPoolManager function modifyLiquidity( PoolKey memory key, IPoolManager.ModifyLiquidityParams memory params, bytes calldata hookData ) external override onlyWhenUnlocked noDelegateCall returns (BalanceDelta callerDelta, BalanceDelta feesAccrued) { PoolId id = key.toId(); Pool.State storage pool = _getPool(id); pool.checkPoolInitialized(); key.hooks.beforeModifyLiquidity(key, params, hookData); BalanceDelta principalDelta; (principalDelta, feesAccrued) = pool.modifyLiquidity( Pool.ModifyLiquidityParams({ owner: msg.sender, tickLower: params.tickLower, tickUpper: params.tickUpper, liquidityDelta: params.liquidityDelta.toInt128(), tickSpacing: key.tickSpacing, salt: params.salt }) ); callerDelta = principalDelta + feesAccrued; // event is emitted before the afterModifyLiquidity call to ensure events are always emitted in order emit ModifyLiquidity(id, msg.sender, params.tickLower, params.tickUpper, params.liquidityDelta); BalanceDelta hookDelta; (callerDelta, hookDelta) = key.hooks.afterModifyLiquidity(key, params, callerDelta, hookData); // if the hook doesnt have the flag to be able to return deltas, hookDelta will always be 0 if (hookDelta != BalanceDeltaLibrary.ZERO_DELTA) _accountPoolBalanceDelta(key, hookDelta, address(key.hooks)); _accountPoolBalanceDelta(key, callerDelta, msg.sender); } /// @inheritdoc IPoolManager function swap(PoolKey memory key, IPoolManager.SwapParams memory params, bytes calldata hookData) external override onlyWhenUnlocked noDelegateCall returns (BalanceDelta swapDelta) { if (params.amountSpecified == 0) SwapAmountCannotBeZero.selector.revertWith(); PoolId id = key.toId(); Pool.State storage pool = _getPool(id); pool.checkPoolInitialized(); BeforeSwapDelta beforeSwapDelta; { int256 amountToSwap; uint24 lpFeeOverride; (amountToSwap, beforeSwapDelta, lpFeeOverride) = key.hooks.beforeSwap(key, params, hookData); // execute swap, account protocol fees, and emit swap event // _swap is needed to avoid stack too deep error swapDelta = _swap( pool, id, Pool.SwapParams({ tickSpacing: key.tickSpacing, zeroForOne: params.zeroForOne, amountSpecified: amountToSwap, sqrtPriceLimitX96: params.sqrtPriceLimitX96, lpFeeOverride: lpFeeOverride }), params.zeroForOne ? key.currency0 : key.currency1 // input token ); } BalanceDelta hookDelta; (swapDelta, hookDelta) = key.hooks.afterSwap(key, params, swapDelta, hookData, beforeSwapDelta); // if the hook doesnt have the flag to be able to return deltas, hookDelta will always be 0 if (hookDelta != BalanceDeltaLibrary.ZERO_DELTA) _accountPoolBalanceDelta(key, hookDelta, address(key.hooks)); _accountPoolBalanceDelta(key, swapDelta, msg.sender); } /// @notice Internal swap function to execute a swap, take protocol fees on input token, and emit the swap event function _swap(Pool.State storage pool, PoolId id, Pool.SwapParams memory params, Currency inputCurrency) internal returns (BalanceDelta) { (BalanceDelta delta, uint256 feeForProtocol, uint24 swapFee, Pool.SwapState memory state) = pool.swap(params); // the fee is on the input currency if (feeForProtocol > 0) _updateProtocolFees(inputCurrency, feeForProtocol); // event is emitted before the afterSwap call to ensure events are always emitted in order emit Swap( id, msg.sender, delta.amount0(), delta.amount1(), state.sqrtPriceX96, state.liquidity, state.tick, swapFee ); return delta; } /// @inheritdoc IPoolManager function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData) external override onlyWhenUnlocked noDelegateCall returns (BalanceDelta delta) { Pool.State storage pool = _getPool(key.toId()); pool.checkPoolInitialized(); key.hooks.beforeDonate(key, amount0, amount1, hookData); delta = pool.donate(amount0, amount1); _accountPoolBalanceDelta(key, delta, msg.sender); key.hooks.afterDonate(key, amount0, amount1, hookData); } /// @inheritdoc IPoolManager function sync(Currency currency) public returns (uint256 balance) { balance = currency.balanceOfSelf(); currency.setReserves(balance); } /// @inheritdoc IPoolManager function take(Currency currency, address to, uint256 amount) external override onlyWhenUnlocked { unchecked { // negation must be safe as amount is not negative _accountDelta(currency, -(amount.toInt128()), msg.sender); currency.transfer(to, amount); } } /// @inheritdoc IPoolManager function settle(Currency currency) external payable override onlyWhenUnlocked returns (uint256 paid) { if (currency.isNative()) { paid = msg.value; } else { if (msg.value > 0) NonZeroNativeValue.selector.revertWith(); uint256 reservesBefore = currency.getReserves(); uint256 reservesNow = sync(currency); paid = reservesNow - reservesBefore; } _accountDelta(currency, paid.toInt128(), msg.sender); } /// @inheritdoc IPoolManager function mint(address to, uint256 id, uint256 amount) external override onlyWhenUnlocked { unchecked { // negation must be safe as amount is not negative _accountDelta(CurrencyLibrary.fromId(id), -(amount.toInt128()), msg.sender); _mint(to, id, amount); } } /// @inheritdoc IPoolManager function burn(address from, uint256 id, uint256 amount) external override onlyWhenUnlocked { _accountDelta(CurrencyLibrary.fromId(id), amount.toInt128(), msg.sender); _burnFrom(from, id, amount); } /// @inheritdoc IPoolManager function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external { if (!key.fee.isDynamicFee() || msg.sender != address(key.hooks)) { UnauthorizedDynamicLPFeeUpdate.selector.revertWith(); } newDynamicLPFee.validate(); PoolId id = key.toId(); _pools[id].setLPFee(newDynamicLPFee); } /// @notice Adds a balance delta in a currency for a target address function _accountDelta(Currency currency, int128 delta, address target) internal { if (delta == 0) return; int256 current = currency.getDelta(target); int256 next = current + delta; if (next == 0) { NonZeroDeltaCount.decrement(); } else if (current == 0) { NonZeroDeltaCount.increment(); } currency.setDelta(target, next); } /// @notice Accounts the deltas of 2 currencies to a target address function _accountPoolBalanceDelta(PoolKey memory key, BalanceDelta delta, address target) internal { _accountDelta(key.currency0, delta.amount0(), target); _accountDelta(key.currency1, delta.amount1(), target); } /// @notice Implementation of the _getPool function defined in ProtocolFees function _getPool(PoolId id) internal view override returns (Pool.State storage) { return _pools[id]; } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.19; import {Currency} from "./types/Currency.sol"; import {IProtocolFeeController} from "./interfaces/IProtocolFeeController.sol"; import {IProtocolFees} from "./interfaces/IProtocolFees.sol"; import {PoolKey} from "./types/PoolKey.sol"; import {ProtocolFeeLibrary} from "./libraries/ProtocolFeeLibrary.sol"; import {Owned} from "solmate/auth/Owned.sol"; import {PoolId, PoolIdLibrary} from "./types/PoolId.sol"; import {Pool} from "./libraries/Pool.sol"; import {CustomRevert} from "./libraries/CustomRevert.sol"; abstract contract ProtocolFees is IProtocolFees, Owned { using ProtocolFeeLibrary for uint24; using PoolIdLibrary for PoolKey; using Pool for Pool.State; using CustomRevert for bytes4; mapping(Currency currency => uint256) public protocolFeesAccrued; IProtocolFeeController public protocolFeeController; uint256 private immutable controllerGasLimit; constructor(uint256 _controllerGasLimit) Owned(msg.sender) { controllerGasLimit = _controllerGasLimit; } /// @inheritdoc IProtocolFees function setProtocolFeeController(IProtocolFeeController controller) external onlyOwner { protocolFeeController = controller; emit ProtocolFeeControllerUpdated(address(controller)); } /// @inheritdoc IProtocolFees function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external { if (msg.sender != address(protocolFeeController)) InvalidCaller.selector.revertWith(); if (!newProtocolFee.isValidProtocolFee()) InvalidProtocolFee.selector.revertWith(); PoolId id = key.toId(); _getPool(id).setProtocolFee(newProtocolFee); emit ProtocolFeeUpdated(id, newProtocolFee); } /// @inheritdoc IProtocolFees function collectProtocolFees(address recipient, Currency currency, uint256 amount) external returns (uint256 amountCollected) { if (msg.sender != address(protocolFeeController)) InvalidCaller.selector.revertWith(); amountCollected = (amount == 0) ? protocolFeesAccrued[currency] : amount; protocolFeesAccrued[currency] -= amountCollected; currency.transfer(recipient, amountCollected); } /// @dev abstract internal function to allow the ProtocolFees contract to access pool state /// @dev this is overriden in PoolManager.sol to give access to the _pools mapping function _getPool(PoolId id) internal virtual returns (Pool.State storage); /// @notice Fetch the protocol fees for a given pool, returning false if the call fails or the returned fees are invalid. /// @dev to prevent an invalid protocol fee controller from blocking pools from being initialized /// the success of this function is NOT checked on initialize and if the call fails, the protocol fees are set to 0. /// @dev the success of this function must be checked when called in setProtocolFee function _fetchProtocolFee(PoolKey memory key) internal returns (bool success, uint24 protocolFee) { if (address(protocolFeeController) != address(0)) { // note that EIP-150 mandates that calls requesting more than 63/64ths of remaining gas // will be allotted no more than this amount, so controllerGasLimit must be set with this // in mind. if (gasleft() < controllerGasLimit) ProtocolFeeCannotBeFetched.selector.revertWith(); (bool _success, bytes memory _data) = address(protocolFeeController).call{gas: controllerGasLimit}( abi.encodeCall(IProtocolFeeController.protocolFeeForPool, (key)) ); // Ensure that the return data fits within a word if (!_success || _data.length > 32) return (false, 0); uint256 returnData; assembly ("memory-safe") { returnData := mload(add(_data, 0x20)) } // Ensure return data does not overflow a uint24 and that the underlying fees are within bounds. (success, protocolFee) = (returnData == uint24(returnData)) && uint24(returnData).isValidProtocolFee() ? (true, uint24(returnData)) : (false, 0); } } function _updateProtocolFees(Currency currency, uint256 amount) internal { unchecked { protocolFeesAccrued[currency] += amount; } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; 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 { 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 { 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 { 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); } library BalanceDeltaLibrary { BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0); function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) { assembly { _amount0 := sar(128, balanceDelta) } } function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) { assembly { _amount1 := signextend(15, balanceDelta) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import {BalanceDelta} from "./BalanceDelta.sol"; // 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)) } } library BeforeSwapDeltaLibrary { 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 { deltaSpecified := sar(128, delta) } } /// extracts int128 from the lower 128 bits of the BeforeSwapDelta /// returned by beforeSwap and afterSwap function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) { assembly ("memory-safe") { deltaUnspecified := signextend(15, delta) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.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 Thrown when a native transfer fails error NativeTransferFailed(); /// @notice Thrown when an ERC20 transfer fails error ERC20TransferFailed(); Currency public constant NATIVE = Currency.wrap(address(0)); function transfer(Currency currency, address to, uint256 amount) internal { // altered from https://github.com/Vectorized/solady/blob/89101d53b7c8784cca935c1f2f6403639cee48b2/src/utils/SafeTransferLib.sol // modified custom error selectors if (currency.isNative()) { assembly ("memory-safe") { // Transfer the ETH and revert if it fails. if iszero(call(gas(), to, amount, 0x00, 0x00, 0x00, 0x00)) { mstore(0x00, 0xf4b3b1bc) // `NativeTransferFailed()`. revert(0x1c, 0x04) } } } else { assembly ("memory-safe") { mstore(0x14, to) // Store the `to` address in [0x20, 0x34). mstore(0x34, amount) // Store the `amount` argument in [0x34, 0x54). // Store the selector of `transfer(address,uint256)` in [0x10, 0x14). // also cleans the upper bits of `to` mstore(0x00, 0xa9059cbb000000000000000000000000) // Perform the transfer, reverting upon failure. if iszero( and( // The arguments of `and` are evaluated from right to left. or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing. call(gas(), currency, 0, 0x10, 0x44, 0x00, 0x20) ) ) { mstore(0x00, 0xf27f64e4) // `ERC20TransferFailed()`. revert(0x1c, 0x04) } mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten. } } } function balanceOfSelf(Currency currency) internal view returns (uint256) { if (currency.isNative()) { 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.isNative()) { return owner.balance; } else { return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner); } } function isNative(Currency currency) internal pure returns (bool) { return Currency.unwrap(currency) == Currency.unwrap(NATIVE); } function toId(Currency currency) internal pure returns (uint256) { return uint160(Currency.unwrap(currency)); } function fromId(uint256 id) internal pure returns (Currency) { return Currency.wrap(address(uint160(id))); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; 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") { poolId := keccak256(poolKey, mul(32, 5)) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import {Currency} from "./Currency.sol"; import {IHooks} from "../interfaces/IHooks.sol"; /// @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 swap fee, capped at 1_000_000. If the first bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000 uint24 fee; /// @notice Ticks that involve positions must be a multiple of tick spacing int24 tickSpacing; /// @notice The hooks of the pool IHooks hooks; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; /** * @dev Slot0 is a packed version of solidity structure. * Using the packaged version saves gas by not storing the structure fields in memory slots. * * Layout: * 24 bits empty | 24 bits lpFee | 24 bits protocolFee | 24 bits tick | 160 bits sqrtPriceX96 * * Fields in the direction from the least significant bit: * * The current price * uint160 sqrtPriceX96; * * The current tick * int24 tick; * * Protocol fee, expressed in hundredths of a bip, upper 12 bits are for 1->0, and the lower 12 are for 0->1 * the maximum is 1000 - meaning the maximum protocol fee is 0.1% * the protocolFee is taken from the input first, then the lpFee is taken from the remaining input * uint24 protocolFee; * * Used for the lp fee, either static at initialize or dynamic via hook * uint24 lpFee; */ type Slot0 is bytes32; using Slot0Library for Slot0 global; library Slot0Library { uint160 internal constant MASK_160_BITS = 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; uint24 internal constant MASK_24_BITS = 0xFFFFFF; uint8 internal constant TICK_OFFSET = 160; uint8 internal constant PROTOCOL_FEE_OFFSET = 184; uint8 internal constant LP_FEE_OFFSET = 208; // #### GETTERS #### function sqrtPriceX96(Slot0 _packed) internal pure returns (uint160 _sqrtPriceX96) { assembly ("memory-safe") { _sqrtPriceX96 := and(MASK_160_BITS, _packed) } } function tick(Slot0 _packed) internal pure returns (int24 _tick) { assembly ("memory-safe") { _tick := signextend(2, shr(TICK_OFFSET, _packed)) } } function protocolFee(Slot0 _packed) internal pure returns (uint24 _protocolFee) { assembly ("memory-safe") { _protocolFee := and(MASK_24_BITS, shr(PROTOCOL_FEE_OFFSET, _packed)) } } function lpFee(Slot0 _packed) internal pure returns (uint24 _lpFee) { assembly ("memory-safe") { _lpFee := and(MASK_24_BITS, shr(LP_FEE_OFFSET, _packed)) } } // #### SETTERS #### function setSqrtPriceX96(Slot0 _packed, uint160 _sqrtPriceX96) internal pure returns (Slot0 _result) { assembly ("memory-safe") { _result := or(and(not(MASK_160_BITS), _packed), and(MASK_160_BITS, _sqrtPriceX96)) } } function setTick(Slot0 _packed, int24 _tick) internal pure returns (Slot0 _result) { assembly ("memory-safe") { _result := or(and(not(shl(TICK_OFFSET, MASK_24_BITS)), _packed), shl(TICK_OFFSET, and(MASK_24_BITS, _tick))) } } function setProtocolFee(Slot0 _packed, uint24 _protocolFee) internal pure returns (Slot0 _result) { assembly ("memory-safe") { _result := or( and(not(shl(PROTOCOL_FEE_OFFSET, MASK_24_BITS)), _packed), shl(PROTOCOL_FEE_OFFSET, and(MASK_24_BITS, _protocolFee)) ) } } function setLpFee(Slot0 _packed, uint24 _lpFee) internal pure returns (Slot0 _result) { assembly ("memory-safe") { _result := or(and(not(shl(LP_FEE_OFFSET, MASK_24_BITS)), _packed), shl(LP_FEE_OFFSET, and(MASK_24_BITS, _lpFee))) } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol"; import {Currency} from "@uniswap/v4-core/src/types/Currency.sol"; import {PathKey} from "../libraries/PathKey.sol"; /// @title Quoter Interface /// @notice Supports quoting the delta amounts from exact input or exact output swaps. /// @notice For each pool also tells you the number of initialized ticks loaded and the sqrt price of the pool after the swap. /// @dev These functions are not marked view because they rely on calling non-view functions and reverting /// to compute the result. They are also not gas efficient and should not be called on-chain. interface IQuoter { error InvalidUnlockCallbackSender(); error InvalidLockCaller(); error InvalidQuoteBatchParams(); error InsufficientAmountOut(); error LockFailure(); error NotSelf(); error UnexpectedRevertBytes(bytes revertData); struct PoolDeltas { int128 currency0Delta; int128 currency1Delta; } struct QuoteExactSingleParams { PoolKey poolKey; bool zeroForOne; address recipient; uint128 exactAmount; uint160 sqrtPriceLimitX96; bytes hookData; } struct QuoteExactParams { Currency exactCurrency; PathKey[] path; address recipient; uint128 exactAmount; } /// @notice Returns the delta amounts for a given exact input swap of a single pool /// @param params The params for the quote, encoded as `QuoteExactInputSingleParams` /// poolKey The key for identifying a V4 pool /// zeroForOne If the swap is from currency0 to currency1 /// recipient The intended recipient of the output tokens /// exactAmount The desired input amount /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap /// hookData arbitrary hookData to pass into the associated hooks /// @return deltaAmounts Delta amounts resulted from the swap /// @return sqrtPriceX96After The sqrt price of the pool after the swap /// @return initializedTicksLoaded The number of initialized ticks that the swap loaded function quoteExactInputSingle(QuoteExactSingleParams calldata params) external returns (int128[] memory deltaAmounts, uint160 sqrtPriceX96After, uint32 initializedTicksLoaded); /// @notice Returns the delta amounts along the swap path for a given exact input swap /// @param params the params for the quote, encoded as 'QuoteExactInputParams' /// currencyIn The input currency of the swap /// path The path of the swap encoded as PathKeys that contains currency, fee, tickSpacing, and hook info /// recipient The intended recipient of the output tokens /// exactAmount The desired input amount /// @return deltaAmounts Delta amounts along the path resulted from the swap /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path /// @return initializedTicksLoadedList List of the initialized ticks that the swap loaded for each pool in the path function quoteExactInput(QuoteExactParams memory params) external returns ( int128[] memory deltaAmounts, uint160[] memory sqrtPriceX96AfterList, uint32[] memory initializedTicksLoadedList ); /// @notice Returns the delta amounts for a given exact output swap of a single pool /// @param params The params for the quote, encoded as `QuoteExactOutputSingleParams` /// poolKey The key for identifying a V4 pool /// zeroForOne If the swap is from currency0 to currency1 /// recipient The intended recipient of the output tokens /// exactAmount The desired input amount /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap /// hookData arbitrary hookData to pass into the associated hooks /// @return deltaAmounts Delta amounts resulted from the swap /// @return sqrtPriceX96After The sqrt price of the pool after the swap /// @return initializedTicksLoaded The number of initialized ticks that the swap loaded function quoteExactOutputSingle(QuoteExactSingleParams calldata params) external returns (int128[] memory deltaAmounts, uint160 sqrtPriceX96After, uint32 initializedTicksLoaded); /// @notice Returns the delta amounts along the swap path for a given exact output swap /// @param params the params for the quote, encoded as 'QuoteExactOutputParams' /// currencyOut The output currency of the swap /// path The path of the swap encoded as PathKeys that contains currency, fee, tickSpacing, and hook info /// recipient The intended recipient of the output tokens /// exactAmount The desired output amount /// @return deltaAmounts Delta amounts along the path resulted from the swap /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path /// @return initializedTicksLoadedList List of the initialized ticks that the swap loaded for each pool in the path function quoteExactOutput(QuoteExactParams memory params) external returns ( int128[] memory deltaAmounts, uint160[] memory sqrtPriceX96AfterList, uint32[] memory initializedTicksLoadedList ); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol"; import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol"; import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol"; import {IUnlockCallback} from "@uniswap/v4-core/src/interfaces/callback/IUnlockCallback.sol"; import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol"; import {Currency} from "@uniswap/v4-core/src/types/Currency.sol"; import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol"; import {PoolIdLibrary} from "@uniswap/v4-core/src/types/PoolId.sol"; import {IQuoter} from "../interfaces/IQuoter.sol"; import {PoolTicksCounter} from "../libraries/PoolTicksCounter.sol"; import {PathKey, PathKeyLib} from "../libraries/PathKey.sol"; import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol"; contract Quoter is IQuoter, IUnlockCallback { using Hooks for IHooks; using PoolIdLibrary for PoolKey; using PathKeyLib for PathKey; using StateLibrary for IPoolManager; /// @dev cache used to check a safety condition in exact output swaps. uint128 private amountOutCached; // v4 Singleton contract IPoolManager public immutable manager; /// @dev min valid reason is 3-words long /// @dev int128[2] + sqrtPriceX96After padded to 32bytes + intializeTicksLoaded padded to 32bytes uint256 internal constant MINIMUM_VALID_RESPONSE_LENGTH = 96; struct QuoteResult { int128[] deltaAmounts; uint160[] sqrtPriceX96AfterList; uint32[] initializedTicksLoadedList; } struct QuoteCache { BalanceDelta curDeltas; uint128 prevAmount; int128 deltaIn; int128 deltaOut; int24 tickBefore; int24 tickAfter; Currency prevCurrency; uint160 sqrtPriceX96After; } /// @dev Only this address may call this function modifier selfOnly() { if (msg.sender != address(this)) revert NotSelf(); _; } constructor(address _poolManager) { manager = IPoolManager(_poolManager); } /// @inheritdoc IQuoter function quoteExactInputSingle(QuoteExactSingleParams memory params) public override returns (int128[] memory deltaAmounts, uint160 sqrtPriceX96After, uint32 initializedTicksLoaded) { try manager.unlock(abi.encodeWithSelector(this._quoteExactInputSingle.selector, params)) {} catch (bytes memory reason) { return _handleRevertSingle(reason); } } /// @inheritdoc IQuoter function quoteExactInput(QuoteExactParams memory params) external returns ( int128[] memory deltaAmounts, uint160[] memory sqrtPriceX96AfterList, uint32[] memory initializedTicksLoadedList ) { try manager.unlock(abi.encodeWithSelector(this._quoteExactInput.selector, params)) {} catch (bytes memory reason) { return _handleRevert(reason); } } /// @inheritdoc IQuoter function quoteExactOutputSingle(QuoteExactSingleParams memory params) public override returns (int128[] memory deltaAmounts, uint160 sqrtPriceX96After, uint32 initializedTicksLoaded) { try manager.unlock(abi.encodeWithSelector(this._quoteExactOutputSingle.selector, params)) {} catch (bytes memory reason) { if (params.sqrtPriceLimitX96 == 0) delete amountOutCached; return _handleRevertSingle(reason); } } /// @inheritdoc IQuoter function quoteExactOutput(QuoteExactParams memory params) public override returns ( int128[] memory deltaAmounts, uint160[] memory sqrtPriceX96AfterList, uint32[] memory initializedTicksLoadedList ) { try manager.unlock(abi.encodeWithSelector(this._quoteExactOutput.selector, params)) {} catch (bytes memory reason) { return _handleRevert(reason); } } /// @inheritdoc IUnlockCallback function unlockCallback(bytes calldata data) external returns (bytes memory) { if (msg.sender != address(manager)) { revert InvalidUnlockCallbackSender(); } (bool success, bytes memory returnData) = address(this).call(data); if (success) return returnData; if (returnData.length == 0) revert LockFailure(); // if the call failed, bubble up the reason /// @solidity memory-safe-assembly assembly { revert(add(returnData, 32), mload(returnData)) } } /// @dev check revert bytes and pass through if considered valid; otherwise revert with different message function validateRevertReason(bytes memory reason) private pure returns (bytes memory) { if (reason.length < MINIMUM_VALID_RESPONSE_LENGTH) { revert UnexpectedRevertBytes(reason); } return reason; } /// @dev parse revert bytes from a single-pool quote function _handleRevertSingle(bytes memory reason) private pure returns (int128[] memory deltaAmounts, uint160 sqrtPriceX96After, uint32 initializedTicksLoaded) { reason = validateRevertReason(reason); (deltaAmounts, sqrtPriceX96After, initializedTicksLoaded) = abi.decode(reason, (int128[], uint160, uint32)); } /// @dev parse revert bytes from a potentially multi-hop quote and return the delta amounts, sqrtPriceX96After, and initializedTicksLoaded function _handleRevert(bytes memory reason) private pure returns ( int128[] memory deltaAmounts, uint160[] memory sqrtPriceX96AfterList, uint32[] memory initializedTicksLoadedList ) { reason = validateRevertReason(reason); (deltaAmounts, sqrtPriceX96AfterList, initializedTicksLoadedList) = abi.decode(reason, (int128[], uint160[], uint32[])); } /// @dev quote an ExactInput swap along a path of tokens, then revert with the result function _quoteExactInput(QuoteExactParams memory params) public selfOnly returns (bytes memory) { uint256 pathLength = params.path.length; QuoteResult memory result = QuoteResult({ deltaAmounts: new int128[](pathLength + 1), sqrtPriceX96AfterList: new uint160[](pathLength), initializedTicksLoadedList: new uint32[](pathLength) }); QuoteCache memory cache; for (uint256 i = 0; i < pathLength; i++) { (PoolKey memory poolKey, bool zeroForOne) = params.path[i].getPoolAndSwapDirection(i == 0 ? params.exactCurrency : cache.prevCurrency); (, cache.tickBefore,,) = manager.getSlot0(poolKey.toId()); (cache.curDeltas, cache.sqrtPriceX96After, cache.tickAfter) = _swap( poolKey, zeroForOne, -int256(int128(i == 0 ? params.exactAmount : cache.prevAmount)), 0, params.path[i].hookData ); (cache.deltaIn, cache.deltaOut) = zeroForOne ? (-cache.curDeltas.amount0(), -cache.curDeltas.amount1()) : (-cache.curDeltas.amount1(), -cache.curDeltas.amount0()); result.deltaAmounts[i] += cache.deltaIn; result.deltaAmounts[i + 1] += cache.deltaOut; cache.prevAmount = zeroForOne ? uint128(cache.curDeltas.amount1()) : uint128(cache.curDeltas.amount0()); cache.prevCurrency = params.path[i].intermediateCurrency; result.sqrtPriceX96AfterList[i] = cache.sqrtPriceX96After; result.initializedTicksLoadedList[i] = PoolTicksCounter.countInitializedTicksLoaded(manager, poolKey, cache.tickBefore, cache.tickAfter); } bytes memory r = abi.encode(result.deltaAmounts, result.sqrtPriceX96AfterList, result.initializedTicksLoadedList); assembly { revert(add(0x20, r), mload(r)) } } /// @dev quote an ExactInput swap on a pool, then revert with the result function _quoteExactInputSingle(QuoteExactSingleParams memory params) public selfOnly returns (bytes memory) { (, int24 tickBefore,,) = manager.getSlot0(params.poolKey.toId()); (BalanceDelta deltas, uint160 sqrtPriceX96After, int24 tickAfter) = _swap( params.poolKey, params.zeroForOne, -int256(int128(params.exactAmount)), params.sqrtPriceLimitX96, params.hookData ); int128[] memory deltaAmounts = new int128[](2); deltaAmounts[0] = -deltas.amount0(); deltaAmounts[1] = -deltas.amount1(); uint32 initializedTicksLoaded = PoolTicksCounter.countInitializedTicksLoaded(manager, params.poolKey, tickBefore, tickAfter); bytes memory result = abi.encode(deltaAmounts, sqrtPriceX96After, initializedTicksLoaded); assembly { revert(add(0x20, result), mload(result)) } } /// @dev quote an ExactOutput swap along a path of tokens, then revert with the result function _quoteExactOutput(QuoteExactParams memory params) public selfOnly returns (bytes memory) { uint256 pathLength = params.path.length; QuoteResult memory result = QuoteResult({ deltaAmounts: new int128[](pathLength + 1), sqrtPriceX96AfterList: new uint160[](pathLength), initializedTicksLoadedList: new uint32[](pathLength) }); QuoteCache memory cache; uint128 curAmountOut; for (uint256 i = pathLength; i > 0; i--) { curAmountOut = i == pathLength ? params.exactAmount : cache.prevAmount; amountOutCached = curAmountOut; (PoolKey memory poolKey, bool oneForZero) = PathKeyLib.getPoolAndSwapDirection( params.path[i - 1], i == pathLength ? params.exactCurrency : cache.prevCurrency ); (, cache.tickBefore,,) = manager.getSlot0(poolKey.toId()); (cache.curDeltas, cache.sqrtPriceX96After, cache.tickAfter) = _swap(poolKey, !oneForZero, int256(uint256(curAmountOut)), 0, params.path[i - 1].hookData); // always clear because sqrtPriceLimitX96 is set to 0 always delete amountOutCached; (cache.deltaIn, cache.deltaOut) = !oneForZero ? (-cache.curDeltas.amount0(), -cache.curDeltas.amount1()) : (-cache.curDeltas.amount1(), -cache.curDeltas.amount0()); result.deltaAmounts[i - 1] += cache.deltaIn; result.deltaAmounts[i] += cache.deltaOut; cache.prevAmount = !oneForZero ? uint128(-cache.curDeltas.amount0()) : uint128(-cache.curDeltas.amount1()); cache.prevCurrency = params.path[i - 1].intermediateCurrency; result.sqrtPriceX96AfterList[i - 1] = cache.sqrtPriceX96After; result.initializedTicksLoadedList[i - 1] = PoolTicksCounter.countInitializedTicksLoaded(manager, poolKey, cache.tickBefore, cache.tickAfter); } bytes memory r = abi.encode(result.deltaAmounts, result.sqrtPriceX96AfterList, result.initializedTicksLoadedList); assembly { revert(add(0x20, r), mload(r)) } } /// @dev quote an ExactOutput swap on a pool, then revert with the result function _quoteExactOutputSingle(QuoteExactSingleParams memory params) public selfOnly returns (bytes memory) { // if no price limit has been specified, cache the output amount for comparison in the swap callback if (params.sqrtPriceLimitX96 == 0) amountOutCached = params.exactAmount; (, int24 tickBefore,,) = manager.getSlot0(params.poolKey.toId()); (BalanceDelta deltas, uint160 sqrtPriceX96After, int24 tickAfter) = _swap( params.poolKey, params.zeroForOne, int256(uint256(params.exactAmount)), params.sqrtPriceLimitX96, params.hookData ); if (amountOutCached != 0) delete amountOutCached; int128[] memory deltaAmounts = new int128[](2); deltaAmounts[0] = -deltas.amount0(); deltaAmounts[1] = -deltas.amount1(); uint32 initializedTicksLoaded = PoolTicksCounter.countInitializedTicksLoaded(manager, params.poolKey, tickBefore, tickAfter); bytes memory result = abi.encode(deltaAmounts, sqrtPriceX96After, initializedTicksLoaded); assembly { revert(add(0x20, result), mload(result)) } } /// @dev Execute a swap and return the amounts delta, as well as relevant pool state /// @notice if amountSpecified > 0, the swap is exactInput, otherwise exactOutput function _swap( PoolKey memory poolKey, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes memory hookData ) private returns (BalanceDelta deltas, uint160 sqrtPriceX96After, int24 tickAfter) { deltas = manager.swap( poolKey, IPoolManager.SwapParams({ zeroForOne: zeroForOne, amountSpecified: amountSpecified, sqrtPriceLimitX96: _sqrtPriceLimitOrDefault(sqrtPriceLimitX96, zeroForOne) }), hookData ); // only exactOut case if (amountOutCached != 0 && amountOutCached != uint128(zeroForOne ? deltas.amount1() : deltas.amount0())) { revert InsufficientAmountOut(); } (sqrtPriceX96After, tickAfter,,) = manager.getSlot0(poolKey.toId()); } /// @dev return either the sqrtPriceLimit from user input, or the max/min value possible depending on trade direction function _sqrtPriceLimitOrDefault(uint160 sqrtPriceLimitX96, bool zeroForOne) private pure returns (uint160) { return sqrtPriceLimitX96 == 0 ? zeroForOne ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1 : sqrtPriceLimitX96; } }
//SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.20; import {Currency} from "@uniswap/v4-core/src/types/Currency.sol"; import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol"; import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol"; struct PathKey { Currency intermediateCurrency; uint24 fee; int24 tickSpacing; IHooks hooks; bytes hookData; } library PathKeyLib { function getPoolAndSwapDirection(PathKey memory params, Currency currencyIn) internal pure returns (PoolKey memory poolKey, bool zeroForOne) { (Currency currency0, Currency currency1) = currencyIn < params.intermediateCurrency ? (currencyIn, params.intermediateCurrency) : (params.intermediateCurrency, currencyIn); zeroForOne = currencyIn == currency0; poolKey = PoolKey(currency0, currency1, params.fee, params.tickSpacing, params.hooks); } }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.19; import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; import {Pool} from "@uniswap/v4-core/src/libraries/Pool.sol"; import {PoolId, PoolIdLibrary} from "@uniswap/v4-core/src/types/PoolId.sol"; import {BitMath} from "@uniswap/v4-core/src/libraries/BitMath.sol"; import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol"; /// @title Helper functions to access pool information /// TODO: Expose other getters on core with extsload. Only use when extsload is available and storage layout is frozen. library PoolGetters { uint256 constant POOL_SLOT = 10; uint256 constant TICKS_OFFSET = 4; uint256 constant TICK_BITMAP_OFFSET = 5; using StateLibrary for IPoolManager; function getNetLiquidityAtTick(IPoolManager poolManager, PoolId poolId, int24 tick) internal view returns (int128 l) { bytes32 value = poolManager.extsload( keccak256(abi.encode(tick, uint256(keccak256(abi.encode(poolId, POOL_SLOT))) + TICKS_OFFSET)) ); assembly { l := shr(128, and(value, shl(128, sub(shl(128, 1), 1)))) } } function getTickBitmapAtWord(IPoolManager poolManager, PoolId poolId, int16 word) internal view returns (uint256 bm) { bm = uint256( poolManager.extsload( keccak256(abi.encode(word, uint256(keccak256(abi.encode(poolId, POOL_SLOT))) + TICK_BITMAP_OFFSET)) ) ); } /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either /// to the left (less than or equal to) or right (greater than) of the given tick /// @param poolManager The mapping in which to compute the next initialized tick /// @param tick The starting tick /// @param tickSpacing The spacing between usable ticks /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick) /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks function getNextInitializedTickWithinOneWord( IPoolManager poolManager, PoolId poolId, int24 tick, int24 tickSpacing, bool lte ) internal view returns (int24 next, bool initialized) { unchecked { int24 compressed = tick / tickSpacing; if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity if (lte) { (int16 wordPos, uint8 bitPos) = position(compressed); // all the 1s at or to the right of the current bitPos uint256 mask = (1 << bitPos) - 1 + (1 << bitPos); // uint256 masked = self[wordPos] & mask; uint256 tickBitmap = poolManager.getTickBitmap(poolId, wordPos); uint256 masked = tickBitmap & mask; // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word initialized = masked != 0; // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick next = initialized ? (compressed - int24(uint24(bitPos - BitMath.mostSignificantBit(masked)))) * tickSpacing : (compressed - int24(uint24(bitPos))) * tickSpacing; } else { // start from the word of the next tick, since the current tick state doesn't matter (int16 wordPos, uint8 bitPos) = position(compressed + 1); // all the 1s at or to the left of the bitPos uint256 mask = ~((1 << bitPos) - 1); uint256 tickBitmap = poolManager.getTickBitmap(poolId, wordPos); uint256 masked = tickBitmap & mask; // if there are no initialized ticks to the left of the current tick, return leftmost in the word initialized = masked != 0; // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick next = initialized ? (compressed + 1 + int24(uint24(BitMath.leastSignificantBit(masked) - bitPos))) * tickSpacing : (compressed + 1 + int24(uint24(type(uint8).max - bitPos))) * tickSpacing; } } } /// @notice Computes the position in the mapping where the initialized bit for a tick lives /// @param tick The tick for which to compute the position /// @return wordPos The key in the mapping containing the word in which the bit is stored /// @return bitPos The bit position in the word where the flag is stored function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) { unchecked { wordPos = int16(tick >> 8); bitPos = uint8(int8(tick % 256)); } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.8.20; import {PoolGetters} from "./PoolGetters.sol"; 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 {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol"; library PoolTicksCounter { using PoolIdLibrary for PoolKey; using StateLibrary for IPoolManager; struct TickCache { int16 wordPosLower; int16 wordPosHigher; uint8 bitPosLower; uint8 bitPosHigher; bool tickBeforeInitialized; bool tickAfterInitialized; } /// @dev This function counts the number of initialized ticks that would incur a gas cost between tickBefore and tickAfter. /// When tickBefore and/or tickAfter themselves are initialized, the logic over whether we should count them depends on the /// direction of the swap. If we are swapping upwards (tickAfter > tickBefore) we don't want to count tickBefore but we do /// want to count tickAfter. The opposite is true if we are swapping downwards. function countInitializedTicksLoaded(IPoolManager self, PoolKey memory key, int24 tickBefore, int24 tickAfter) internal view returns (uint32 initializedTicksLoaded) { TickCache memory cache; { // Get the key and offset in the tick bitmap of the active tick before and after the swap. int16 wordPos = int16((tickBefore / key.tickSpacing) >> 8); uint8 bitPos = uint8(uint24((tickBefore / key.tickSpacing) % 256)); int16 wordPosAfter = int16((tickAfter / key.tickSpacing) >> 8); uint8 bitPosAfter = uint8(uint24((tickAfter / key.tickSpacing) % 256)); // In the case where tickAfter is initialized, we only want to count it if we are swapping downwards. // If the initializable tick after the swap is initialized, our original tickAfter is a // multiple of tick spacing, and we are swapping downwards we know that tickAfter is initialized // and we shouldn't count it. uint256 bmAfter = self.getTickBitmap(key.toId(), wordPosAfter); cache.tickAfterInitialized = ((bmAfter & (1 << bitPosAfter)) > 0) && ((tickAfter % key.tickSpacing) == 0) && (tickBefore > tickAfter); // In the case where tickBefore is initialized, we only want to count it if we are swapping upwards. // Use the same logic as above to decide whether we should count tickBefore or not. uint256 bmBefore = self.getTickBitmap(key.toId(), wordPos); cache.tickBeforeInitialized = ((bmBefore & (1 << bitPos)) > 0) && ((tickBefore % key.tickSpacing) == 0) && (tickBefore < tickAfter); if (wordPos < wordPosAfter || (wordPos == wordPosAfter && bitPos <= bitPosAfter)) { cache.wordPosLower = wordPos; cache.bitPosLower = bitPos; cache.wordPosHigher = wordPosAfter; cache.bitPosHigher = bitPosAfter; } else { cache.wordPosLower = wordPosAfter; cache.bitPosLower = bitPosAfter; cache.wordPosHigher = wordPos; cache.bitPosHigher = bitPos; } } // Count the number of initialized ticks crossed by iterating through the tick bitmap. // Our first mask should include the lower tick and everything to its left. uint256 mask = type(uint256).max << cache.bitPosLower; while (cache.wordPosLower <= cache.wordPosHigher) { // If we're on the final tick bitmap page, ensure we only count up to our // ending tick. if (cache.wordPosLower == cache.wordPosHigher) { mask = mask & (type(uint256).max >> (255 - cache.bitPosHigher)); } uint256 bmLower = self.getTickBitmap(key.toId(), cache.wordPosLower); uint256 masked = bmLower & mask; initializedTicksLoaded += countOneBits(masked); cache.wordPosLower++; // Reset our mask so we consider all bits on the next iteration. mask = type(uint256).max; } if (cache.tickAfterInitialized) { initializedTicksLoaded -= 1; } if (cache.tickBeforeInitialized) { initializedTicksLoaded -= 1; } return initializedTicksLoaded; } function countOneBits(uint256 x) private pure returns (uint16) { uint16 bits = 0; while (x != 0) { bits++; x &= (x - 1); } return bits; } }
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Simple single owner authorization mixin. /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Owned.sol) abstract contract Owned { /*////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event OwnershipTransferred(address indexed user, address indexed newOwner); /*////////////////////////////////////////////////////////////// OWNERSHIP STORAGE //////////////////////////////////////////////////////////////*/ address public owner; modifier onlyOwner() virtual { require(msg.sender == owner, "UNAUTHORIZED"); _; } /*////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor(address _owner) { owner = _owner; emit OwnershipTransferred(address(0), _owner); } /*////////////////////////////////////////////////////////////// OWNERSHIP LOGIC //////////////////////////////////////////////////////////////*/ function transferOwnership(address newOwner) public virtual onlyOwner { owner = newOwner; emit OwnershipTransferred(msg.sender, newOwner); } }
{ "evmVersion": "cancun", "optimizer": { "enabled": true, "runs": 1000 }, "viaIR": true, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } } }
Contract ABI
API[{"inputs":[{"internalType":"uint256","name":"controllerGasLimit","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AlreadyUnlocked","type":"error"},{"inputs":[],"name":"CurrenciesOutOfOrderOrEqual","type":"error"},{"inputs":[],"name":"CurrencyNotSettled","type":"error"},{"inputs":[],"name":"DelegateCallNotAllowed","type":"error"},{"inputs":[],"name":"InvalidCaller","type":"error"},{"inputs":[],"name":"InvalidProtocolFee","type":"error"},{"inputs":[],"name":"ManagerLocked","type":"error"},{"inputs":[],"name":"NonZeroNativeValue","type":"error"},{"inputs":[],"name":"PoolNotInitialized","type":"error"},{"inputs":[],"name":"ProtocolFeeCannotBeFetched","type":"error"},{"inputs":[],"name":"SwapAmountCannotBeZero","type":"error"},{"inputs":[],"name":"TickSpacingTooLarge","type":"error"},{"inputs":[],"name":"TickSpacingTooSmall","type":"error"},{"inputs":[],"name":"UnauthorizedDynamicLPFeeUpdate","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":true,"internalType":"uint256","name":"id","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"PoolId","name":"id","type":"bytes32"},{"indexed":true,"internalType":"Currency","name":"currency0","type":"address"},{"indexed":true,"internalType":"Currency","name":"currency1","type":"address"},{"indexed":false,"internalType":"uint24","name":"fee","type":"uint24"},{"indexed":false,"internalType":"int24","name":"tickSpacing","type":"int24"},{"indexed":false,"internalType":"contract IHooks","name":"hooks","type":"address"}],"name":"Initialize","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"id","type":"bytes32"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"int24","name":"tickLower","type":"int24"},{"indexed":false,"internalType":"int24","name":"tickUpper","type":"int24"},{"indexed":false,"internalType":"int256","name":"liquidityDelta","type":"int256"}],"name":"ModifyLiquidity","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"OperatorSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"protocolFeeController","type":"address"}],"name":"ProtocolFeeControllerUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"id","type":"bytes32"},{"indexed":false,"internalType":"uint24","name":"protocolFee","type":"uint24"}],"name":"ProtocolFeeUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"id","type":"bytes32"},{"indexed":false,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"int128","name":"amount0","type":"int128"},{"indexed":false,"internalType":"int128","name":"amount1","type":"int128"},{"indexed":false,"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"indexed":false,"internalType":"uint128","name":"liquidity","type":"uint128"},{"indexed":false,"internalType":"int24","name":"tick","type":"int24"},{"indexed":false,"internalType":"uint24","name":"fee","type":"uint24"}],"name":"Swap","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"uint256","name":"id","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"MAX_TICK_SPACING","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MIN_TICK_SPACING","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"burn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"Currency","name":"currency","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"collectProtocolFees","outputs":[{"internalType":"uint256","name":"amountCollected","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"name":"donate","outputs":[{"internalType":"BalanceDelta","name":"delta","type":"int256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"slot","type":"bytes32"}],"name":"extsload","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"startSlot","type":"bytes32"},{"internalType":"uint256","name":"nSlots","type":"uint256"}],"name":"extsload","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32[]","name":"slots","type":"bytes32[]"}],"name":"extsload","outputs":[{"internalType":"bytes32[]","name":"","type":"bytes32[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32[]","name":"slots","type":"bytes32[]"}],"name":"exttload","outputs":[{"internalType":"bytes32[]","name":"","type":"bytes32[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"slot","type":"bytes32"}],"name":"exttload","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"name":"initialize","outputs":[{"internalType":"int24","name":"tick","type":"int24"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"isOperator","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"mint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"components":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"int256","name":"liquidityDelta","type":"int256"},{"internalType":"bytes32","name":"salt","type":"bytes32"}],"internalType":"struct IPoolManager.ModifyLiquidityParams","name":"params","type":"tuple"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"name":"modifyLiquidity","outputs":[{"internalType":"BalanceDelta","name":"callerDelta","type":"int256"},{"internalType":"BalanceDelta","name":"feesAccrued","type":"int256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"protocolFeeController","outputs":[{"internalType":"contract IProtocolFeeController","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"Currency","name":"currency","type":"address"}],"name":"protocolFeesAccrued","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setOperator","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint24","name":"newProtocolFee","type":"uint24"}],"name":"setProtocolFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IProtocolFeeController","name":"controller","type":"address"}],"name":"setProtocolFeeController","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"Currency","name":"currency","type":"address"}],"name":"settle","outputs":[{"internalType":"uint256","name":"paid","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"components":[{"internalType":"bool","name":"zeroForOne","type":"bool"},{"internalType":"int256","name":"amountSpecified","type":"int256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"}],"internalType":"struct IPoolManager.SwapParams","name":"params","type":"tuple"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"name":"swap","outputs":[{"internalType":"BalanceDelta","name":"swapDelta","type":"int256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"Currency","name":"currency","type":"address"}],"name":"sync","outputs":[{"internalType":"uint256","name":"balance","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"Currency","name":"currency","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"take","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"unlock","outputs":[{"internalType":"bytes","name":"result","type":"bytes"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint24","name":"newDynamicLPFee","type":"uint24"}],"name":"updateDynamicLPFee","outputs":[],"stateMutability":"nonpayable","type":"function"}]
Contract Creation Code
60c034620000a557601f62004be438819003918201601f19168301916001600160401b03831184841017620000a957808492602094604052833981010312620000a557515f80546001600160a01b03191633908117825560405192917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08180a36080523060a052614b269081620000be823960805181612c52015260a051816127500152f35b5f80fd5b634e487b7160e01b5f52604160045260245ffdfe6080806040526004361015610012575f80fd5b5f3560e01c908162fdd58e146122c45750806301ffc9a71461222357806307eff0dd14612208578063095bcdb61461216b5780630b0d9c09146120fb578063156e29f6146120575780631e2eaeaf1461203b578063234266d714611e195780632d77138914611d9957806335fd631a14611d48578063426a849314611cd357806348c8949114611af55780635275965114611a1f578063558a729714611994578063598af9e71461193a5780635a6bcfda1461100e57806360460f0614610ff2578063695c5bf514610b825780636a256b2914610a6a5780637e87ce7d1461097a5780638161b874146108d65780638da5cb5b146108b157806397e8cd4e146108795780639bf6645f14610843578063a584119414610820578063b6363cf2146107cd578063dbd035ff14610797578063f02de3b214610771578063f135baaa14610755578063f2fde38b146106de578063f3cd914c14610443578063f5298aca146102e45763fe99049a14610186575f80fd5b346102e05760803660031901126102e05761019f612303565b6101a7612319565b90604435917f1b3d7edb2e9c0b0e7c525b20aaaef0f5940d2ed71663c7d39266ecafac72885961024f606435936001600160a01b038091169384331415806102bf575b61025d575b845f52600460205260405f20875f5260205260405f206102108782546124f6565b90551693845f52600460205260405f20865f5260205260405f20610235828254612503565b905560408051338152602081019290925290918291820190565b0390a4602060405160018152f35b845f5260206005815260405f20335f52815260405f20885f52815260405f2054875f19820361028f575b5050506101ef565b610298916124f6565b90865f526005815260405f20335f52815260405f2090895f525260405f20555f8087610287565b50845f52600360205260405f20335f5260205260ff60405f205416156101ea565b5f80fd5b346102e0576102f23661232f565b7fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab239291925c1561041b577f1b3d7edb2e9c0b0e7c525b20aaaef0f5940d2ed71663c7d39266ecafac7288596103935f936001600160a01b0390610361610357866125fb565b3390848a16612641565b169233841415806103fa575b610398575b838552600460205260408520868652602052604085206102358282546124f6565b0390a4005b838552602060058152604086203387528152604086208787528152604086205482871982036103ca575b505050610372565b6103d3916124f6565b908587526005815260408720338852815260408720908888525260408620558680826103c2565b5083855260036020526040852033865260205260ff6040862054161561036d565b7f54e3ca0d000000000000000000000000000000000000000000000000000000005f5260045ffd5b346102e0576101203660031901126102e05761045e366123e1565b60603660a31901126102e0576040519067ffffffffffffffff60608301818111848210176106ca5760405260a43580151581036102e0578352602083019060c435825260e4356001600160a01b03811681036102e0576040850152610104359081116102e0576104d290369060040161245a565b917fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab235c1561041b57610502612746565b51156106a25782828261056b87847f40e9cecb9f5f1f1c5b9c97dec2917b7ee92e57ba5563708daca94dd84ad7112f60e062ffffff6105c4816001600160a01b0360209f61064f9e61063d9e6105779260a08b209a8b5f5260206006905260405f209d8e6127a0565b85608082015116612e55565b8a8f9395929f60600151958560408351151593015116916040519761059b89612391565b60020b885260208801526040870152606086015216608084015288511561069757511697613bd5565b939298829192610676575b50506001600160a01b036040840151169260606001600160801b0360a08301511691015160020b90604051943386528a60801d600f0b60208701528a600f0b60408701526060860152608085015260a08401521660c0820152a2876001600160a01b0360808201511661302d565b80939193610657575b50823391612857565b604051908152f35b610670906001600160a01b036080840151169083612857565b84610646565b6001600160a01b03165f528f6001905260405f209081540190558f806105cf565b602001511697613bd5565b7fbe8b8507000000000000000000000000000000000000000000000000000000005f5260045ffd5b634e487b7160e01b5f52604160045260245ffd5b346102e05760203660031901126102e05773ffffffffffffffffffffffffffffffffffffffff1961070d612303565b5f54906001600160a01b03906107268284163314612510565b1691829116175f55337f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f80a3005b346102e05760203660031901126102e0576004355c5f5260205ff35b346102e0575f3660031901126102e05760206001600160a01b0360025416604051908152f35b346102e0576107a5366124a9565b604060045f3760051b604001809160405b8135548152602091820191018281106107b657825ff35b346102e05760403660031901126102e0576107e6612303565b6107ee612319565b906001600160a01b038091165f52600360205260405f2091165f52602052602060ff60405f2054166040519015158152f35b346102e05760203660031901126102e057602061064f61083e612303565b6125b1565b346102e057610851366124a9565b604060045f3760051b604001809160405b81355c81526020918201910182811061086257825ff35b346102e05760203660031901126102e0576001600160a01b0361089a612303565b165f526001602052602060405f2054604051908152f35b346102e0575f3660031901126102e05760206001600160a01b035f5416604051908152f35b346102e05760603660031901126102e0576108ef612303565b6108f7612319565b6044356001600160a01b03806002541633036109525760209361064f928061094a57508184165f526001855260405f20549384925b81165f526001865260405f206109438482546124f6565b90556126d4565b93849261092c565b7f48f5c3ed000000000000000000000000000000000000000000000000000000005f5260045ffd5b346102e05760c03660031901126102e057610994366123e1565b61099c6123cf565b906001600160a01b0360025416330361095257623e900082106103e9610fff8416101615610a4257602060a07fe9c42593e71f84403b84352cd168d693e2c9fcd1fdbcc3feb21d92b43e6696f9922092835f526006825260405f20610a00816127a0565b805462ffffff60b81b8360b81b16907fffffffffffff000000ffffffffffffffffffffffffffffffffffffffffffffff1617905562ffffff60405191168152a2005b7fba97f838000000000000000000000000000000000000000000000000000000005f5260045ffd5b60203660031901126102e057610a7e612303565b7fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab235c1561041b576001600160a01b038116610acc5760209061064f34915b610ac5836125fb565b3391612641565b34610b5a577f1e0745a7db1623981f0b2a5d4232364c00787266eb75ad546f190e6cebe9bd955f528060205260405f205c908115610b32576020915f198114610b2b575b610b2561064f91610b20846125b1565b6124f6565b91610abc565b505f610b10565b7f8774be48000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f19d245cf000000000000000000000000000000000000000000000000000000005f5260045ffd5b346102e05760e03660031901126102e057610b9c366123e1565b6001600160a01b0360a4351660a435036102e05760c43567ffffffffffffffff81116102e057610bd090369060040161245a565b9091610bda612746565b617fff606082015160020b13610fca576001606082015160020b12610fa2576001600160a01b038151166001600160a01b036020830151161115610f7a576001600160a01b03608082015116610c3962ffffff60408401511682612b62565b15610f4f5750610c5162ffffff604083015116612c13565b9160808201516001600160a01b03811690813303610e7a575b505060a0822090610c7a83612c30565b959050825f52600660205260405f2080546001600160a01b0316610e525760209662ffffff60d01b610cad60a435613902565b9760d01b169062ffffff60b81b6001600160a01b0360a4351662ffffff60a01b8a60a01b16179160b81b16171790556080840151916001600160a01b0383163303610d74575b5050507f3fd553db44f207b1f41348cfc4d251860814af9eadc470e8e7895e4d120511f460806001600160a01b03845116926001600160a01b0387860151169462ffffff604082015116906001600160a01b0384606083015160020b92015116916040519384528984015260408301526060820152a36040519060020b8152f35b611000831615610cf357610e4992610e436001600160a01b0392610e356040519586927fa910f80f000000000000000000000000000000000000000000000000000000008d850152336024850152610e0d604485018c608090816001600160a01b039182815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b8660a4351660e48501528b60020b610104850152610120610124850152610144840191612591565b03601f1981018552846123ad565b166131a6565b50848080610cf3565b7f7983c051000000000000000000000000000000000000000000000000000000005f5260045ffd5b61200016610e89575b80610c6a565b610f4890604051907f3440d820000000000000000000000000000000000000000000000000000000006020830152336024830152610f086044830186608090816001600160a01b039182815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b6001600160a01b0360a4351660e4830152610100610104830152610f4382610f356101248201878b612591565b03601f1981018452836123ad565b6131a6565b5084610e83565b7fe65af6a0000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b7feaa6c6eb000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f16fe7696000000000000000000000000000000000000000000000000000000005f5260045ffd5b7fb02b5dc2000000000000000000000000000000000000000000000000000000005f5260045ffd5b346102e0575f3660031901126102e0576020604051617fff8152f35b346102e0576101403660031901126102e057611029366123e1565b60803660a31901126102e0576040519061104282612359565b60a4358060020b81036102e057825260c4358060020b81036102e057602083015260e43560408301526101043560608301526101243567ffffffffffffffff81116102e05761109590369060040161245a565b92907fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab235c1561041b576110c6612746565b60a0832093845f52600660205260405f20906110e1826127a0565b60808501516001600160a01b03811690813303611861575b5050835160020b92602085015160020b966111176040870151612964565b95606088015160020b9860608201516040519a6111338c612375565b338c528860208d01528260408d015289600f0b60608d015260808c015260a08b01525f908088121561183257620d89e719881261180657620d89e881136117db57604051986111818a612359565b5f8a525f60208b01525f60408b01525f60608b015280600f0b6115ad575b885f526004880160205260405f2098825f5260405f20895460a01c60020b8281125f1461155b575060028060018d0154600184015490039c015491015490039c5b60a06001600160a01b0382511691015160265283600652816003525f52603a600c205f6026525f526006890160205260405f209889549a83600f0b155f14611515576001600160801b038c16156114ed5761128060409f6113359c61127a916113479f5b60018301956112726001600160801b0360026112658286168b5486036132cd565b96019316835485036132cd565b9655556125fb565b916125fb565b6001600160801b03169060801b179b5f84600f0b12611483575b5082600f0b611372575b505050506112cb6112bc8960801d8360801d01612964565b9189600f0b90600f0b01612964565b6001600160801b03169060801b1791815160020b90602083015160020b8b840151908c5193845260208401528b8301527f541c041c2cce48e614b3de043c9280f06b6164c0a1741649e2de3c3d375f797460603393a3876001600160a01b03608082015116612a3b565b80949194611353575b50833391612857565b82519182526020820152f35b61136c906001600160a01b036080840151169083612857565b8561133e565b809192939450548060a01c60020b906001600160a01b0316908381125f146113cd57505050916113bb916113b56113ab6113c0956134e4565b91600f0b926134e4565b9061386c565b612964565b60801b5b8a8080806112a4565b948091939295125f14611458576113bb600393926113fe6113bb611411946113f889600f0b916134e4565b8761386c565b9361140c87600f0b926134e4565b6137fe565b6001600160801b03169060801b179201906fffffffffffffffffffffffffffffffff196001600160801b0361144d845493600f0b8285166138ab565b1691161790556113c4565b915061147593509161146f6113ab6113bb946134e4565b906137fe565b6001600160801b03166113c4565b808f91516114c3575b0151611499575b8e61129a565b6114be848260049160020b5f52016020525f6002604082208281558260018201550155565b611493565b6114e8848460049160020b5f52016020525f6002604082208281558260018201550155565b61148c565b7faefeb924000000000000000000000000000000000000000000000000000000005f5260045ffd5b61128060409f6113359c61127a916113479f6001600160801b0361153e8a600f0b8284166138ab565b166fffffffffffffffffffffffffffffffff198216178355611244565b909a9084136115815760028060018d0154600184015490039c015491015490039c6111e0565b99600260018b015460018d01549003600183015490039b81808d0154910154900391015490039c6111e0565b885f5260048801602052886001600160801b0360405f208054906115f3838316928d6115dc88600f0b866138ab565b9685156117ac575b505086600f0b9060801d612ff5565b60801b841790558c60208385169101521591161514158a52815f526004880160205260405f2080546001600160801b03811661163284600f0b826138ab565b928115611785575b6f7fffffffffffffffffffffffffffffff19600f86810b608086901d90910b039081126f7fffffffffffffffffffffffffffffff90911317611771576001600160801b039285600f0b9060801d600f0b0360801b841790558c606083851691015215911615141560408b0152898c5f83600f0b12156116f9575b50516116df575b60408a01511561119f576116da60808d015160020b8360058b016134ab565b61119f565b6116f460808d015160020b8a60058b016134ab565b6116bb565b60016001600160801b03602060808294015160020b94015116928080620d89e71905028180620d89e8050203050181041680911161175e576001600160801b0360608c0151161161174b57898c6116b4565b5063b8e3c38560e01b5f5260045260245ffd5b8963b8e3c38560e01b5f5260045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b8b5460a01c60020b861361163a5760018c0154600182015560028c0154600282015561163a565b815460a01c60020b12156117c1575b8f6115e4565b80600160029201546001860155015460028401558d6117bb565b7f1ad777f8000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b877fd5e2f7ab000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b877fc4433ed5000000000000000000000000000000000000000000000000000000005f5260045260245260445ffd5b5f60408701511380809161192d575b156118c25750506040517f259982e50000000000000000000000000000000000000000000000000000000060208201526118b991610f4382610f3586898b8d33602487016128c2565b505b86806110f9565b15908161191f575b506118d6575b506118bb565b6040517f21d0ee7000000000000000000000000000000000000000000000000000000000602082015261191891610f4382610f3586898b8d33602487016128c2565b50866118d0565b6102009150161515886118ca565b5061080082161515611870565b346102e05760603660031901126102e057611953612303565b61195b612319565b906001600160a01b038091165f52600560205260405f2091165f5260205260405f206044355f52602052602060405f2054604051908152f35b346102e05760403660031901126102e0576119ad612303565b6024358015158091036102e057335f5260036020526001600160a01b0360405f20921691825f5260205260405f2060ff1981541660ff83161790556040519081527fceb576d9f15e4e200fdb5096d64d5dfd667e16def20c1eefd14256d8e3faa26760203392a3602060405160018152f35b346102e05760c03660031901126102e057611a39366123e1565b611a416123cf565b906280000062ffffff60408301511614801590611ade575b611ab65760a090611a6983612889565b205f52600660205260405f2090611a7f826127a0565b81547fffffff000000ffffffffffffffffffffffffffffffffffffffffffffffffffff1660d09190911b62ffffff60d01b16179055005b7f30d21641000000000000000000000000000000000000000000000000000000005f5260045ffd5b506001600160a01b03608082015116331415611a59565b346102e0576020806003193601126102e05767ffffffffffffffff906004358281116102e057611b2990369060040161245a565b91907fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab2392835c611cab57611b98915f916001865d60405193849283927f91dd73460000000000000000000000000000000000000000000000000000000084528760048501526024840191612591565b038183335af1938415611ca0575f94611c2f575b50507f7d4b3164c6e45b97e7d87b7125a44c5828d005af88f9d751cfd78729c5d99a0b5c611c0757611bf9925f6040935d8251938285938452825192818480938701528686019101612488565b601f01601f19168101030190f35b7f5212cba1000000000000000000000000000000000000000000000000000000005f5260045ffd5b909193503d805f843e611c4281846123ad565b82019184818403126102e05780519182116102e0570181601f820112156102e0578051611c6e81612575565b92611c7c60405194856123ad565b8184528582840101116102e057611c9891858085019101612488565b918380611bac565b6040513d5f823e3d90fd5b7f5090d6c6000000000000000000000000000000000000000000000000000000005f5260045ffd5b346102e057611ce13661232f565b919091335f5260056020526001600160a01b0360405f20921691825f5260205260405f20835f526020528060405f20556040519081527fb3fd5071835887567a0671151121894ddccc2842f1d10bedad13e0d17cace9a760203392a4602060405160018152f35b346102e05760403660031901126102e05760043560209060205f5260243560051b8060205260400191829160018260405b835481520191019183821015611d955791906001908390611d79565b835ff35b346102e05760203660031901126102e0576004356001600160a01b038082168092036102e0577fb4bd8ef53df690b9943d3318996006dbb82a25f54719d8c8035b516a2a5b8acc91611df16020925f54163314612510565b8073ffffffffffffffffffffffffffffffffffffffff196002541617600255604051908152a1005b346102e0576101003660031901126102e057611e34366123e1565b60c43560a43560e43567ffffffffffffffff81116102e057611e5a90369060040161245a565b9190927fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab235c1561041b57611e8c612746565b60a085205f52600660205260405f2093611ea5856127a0565b60808601958651926001600160a01b039384811690813303611fe3575b50506001600160801b039788600389015416978815611fbb57602099611ee7886125fb565b5f0390611ef3856125fb565b5f03169060801b179887611fa2575b83611f87575b5050611f15338985612857565b5193841693843303611f2c575b8888604051908152f35b601016611f3a575b80611f22565b611f7b95610f4393610f35926040519788957fe1b4af69000000000000000000000000000000000000000000000000000000008d88015233602488016127d9565b50828080808080611f34565b611f936002918561324c565b91019081540190558980611f08565b611fac818961324c565b60018301908154019055611f02565b7fa74f97ab000000000000000000000000000000000000000000000000000000005f5260045ffd5b602016611ff1575b80611ec2565b6040517fb6a8b0fa00000000000000000000000000000000000000000000000000000000602082015261203491610f4382610f358b89888d8b33602488016127d9565b5088611feb565b346102e05760203660031901126102e057600435545f5260205ff35b346102e0576120653661232f565b90917fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab235c1561041b577f1b3d7edb2e9c0b0e7c525b20aaaef0f5940d2ed71663c7d39266ecafac7288596103935f926001600160a01b03906120d86120c9876125fb565b8603600f0b3390848a16612641565b169384845260046020526040842086855260205260408420610235828254612503565b346102e05760603660031901126102e057612114612303565b61211c612319565b604435907fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab235c1561041b5761216992612164612157846125fb565b5f03600f0b339083612641565b6126d4565b005b346102e0576001600160a01b036121813661232f565b91929092335f52600460205260405f20845f5260205260405f206121a68482546124f6565b90551690815f52600460205260405f20835f5260205260405f206121cb828254612503565b9055604080513380825260208201939093527f1b3d7edb2e9c0b0e7c525b20aaaef0f5940d2ed71663c7d39266ecafac728859918190810161024f565b346102e0575f3660031901126102e057602060405160018152f35b346102e05760203660031901126102e0576004357fffffffff0000000000000000000000000000000000000000000000000000000081168091036102e057807f01ffc9a7000000000000000000000000000000000000000000000000000000006020921490811561229a575b506040519015158152f35b7f0f632fb3000000000000000000000000000000000000000000000000000000009150148261228f565b346102e05760403660031901126102e0576020906001600160a01b036122e8612303565b165f526004825260405f206024355f52825260405f20548152f35b600435906001600160a01b03821682036102e057565b602435906001600160a01b03821682036102e057565b60609060031901126102e0576004356001600160a01b03811681036102e057906024359060443590565b6080810190811067ffffffffffffffff8211176106ca57604052565b60c0810190811067ffffffffffffffff8211176106ca57604052565b60a0810190811067ffffffffffffffff8211176106ca57604052565b90601f8019910116810190811067ffffffffffffffff8211176106ca57604052565b60a4359062ffffff821682036102e057565b60a09060031901126102e057604051906123fa82612391565b6001600160a01b038260043582811681036102e057815260243582811681036102e057602082015260443562ffffff811681036102e05760408201526064358060020b81036102e057606082015260843591821682036102e05760800152565b9181601f840112156102e05782359167ffffffffffffffff83116102e057602083818601950101116102e057565b5f5b8381106124995750505f910152565b818101518382015260200161248a565b9060206003198301126102e05760043567ffffffffffffffff928382116102e057806023830112156102e05781600401359384116102e05760248460051b830101116102e0576024019190565b9190820391821161177157565b9190820180921161177157565b1561251757565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600c60248201527f554e415554484f52495a454400000000000000000000000000000000000000006044820152fd5b67ffffffffffffffff81116106ca57601f01601f191660200190565b908060209392818452848401375f828201840152601f01601f1916010190565b906125bb82612dcb565b91829083156125f2575b7f1e0745a7db1623981f0b2a5d4232364c00787266eb75ad546f190e6cebe9bd955f5260205260405f205d565b5f1991506125c5565b6f8000000000000000000000000000000081101561261957600f0b90565b6393dafdf15f526004601cfd5b9190915f838201938412911290801582169115161761177157565b90600f0b9182156126cf57805f528160205261266260405f205c9384612626565b928361269e57507f7d4b3164c6e45b97e7d87b7125a44c5828d005af88f9d751cfd78729c5d99a0b805c5f1901905d5b5f5260205260405f205d565b612692577f7d4b3164c6e45b97e7d87b7125a44c5828d005af88f9d751cfd78729c5d99a0b6001815c01905d612692565b505050565b6001600160a01b0381166126ff57505f80809381935af1156126f257565b63f4b3b1bc5f526004601cfd5b60105f60449260209582956014526034526fa9059cbb00000000000000000000000082525af13d1560015f5114171615612739575f603452565b63f27f64e45f526004601cfd5b6001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016300361277857565b7f0d89438e000000000000000000000000000000000000000000000000000000005f5260045ffd5b546001600160a01b0316156127b157565b7f486aa307000000000000000000000000000000000000000000000000000000005f5260045ffd5b919261283c612854979592946001600160a01b03610120961685526020850190608090816001600160a01b039182815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b60c083015260e0820152816101008201520191612591565b90565b90612887929160206001600160a01b039161287a85848351168660801d90612641565b01511690600f0b90612641565b565b62ffffff620f424091161161289a57565b7ffc5bee12000000000000000000000000000000000000000000000000000000005f5260045ffd5b90916128549593612927612956926001600160a01b03610160961685526020850190608090816001600160a01b039182815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b8051600290810b60c08501526020820151900b60e0840152604081015161010084015260600151610120830152565b816101408201520191612591565b806f800000000000000000000000000000000160801c1561298c576393dafdf15f526004601cfd5b600f0b90565b91612854969491936129f8612a27926001600160a01b03610180971686526020860190608090816001600160a01b039182815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b8051600290810b60c08601526020820151900b60e0850152604081015161010085015260600151610120840152565b610140820152816101608201520191612591565b929593945f956001600160a01b0385163314612b5857875f6040860151135f14612aea576104008616612a71575b505050505050565b612ade96989750612acb92612ad796959492612abd926040519687957f5a2a81000000000000000000000000000000000000000000000000000000000060208801523360248801612992565b03601f1981018352826123ad565b600282161515916138b7565b80926138ce565b915f8080808080612a69565b94939291906101008516612b0057505050505050565b612ade969850859750612b4c9291612abd91612ad7976040519687957f8db2b6520000000000000000000000000000000000000000000000000000000060208801523360248801612992565b600182161515916138b7565b505f955050505050565b608081161580612c07575b612bdd57604081161580612bfb575b612bdd5761040081161580612bef575b612bdd5761010081161580612be3575b612bdd576001600160a01b038116612bbd575062ffffff1662800000141590565b613fff161590811591612bce575090565b62800000915062ffffff161490565b50505f90565b50600181161515612b9c565b50600281161515612b8c565b50600481161515612b7c565b50600881161515612b6d565b6280000062ffffff821614612c2b5761285481612889565b505f90565b5f915f916001600160a01b03600254169081612c4a575050565b91935091505a7f0000000000000000000000000000000000000000000000000000000000000000809110612da35760405191612cef60208401917f553bfc370000000000000000000000000000000000000000000000000000000083526024850190608090816001600160a01b039182815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b60a4835260e0830183811067ffffffffffffffff8211176106ca575f94859485926040525193f13d15612d9b573d90612d2782612575565b91612d3560405193846123ad565b82523d5f602084013e5b158015612d90575b612d89576020015162ffffff8116908181149081612d71575b5015612d6b57600191565b505f8091565b90506103e9610fff623e90008410921610165f612d60565b505f905f90565b506020815111612d47565b606090612d3f565b7f1ee49702000000000000000000000000000000000000000000000000000000005f5260045ffd5b6001600160a01b031680612dde57504790565b6020602491604051928380927f70a082310000000000000000000000000000000000000000000000000000000082523060048301525afa908115611ca0575f91612e26575090565b90506020813d602011612e4d575b81612e41602093836123ad565b810103126102e0575190565b3d9150612e34565b949192945f945f946020810151976001600160a01b0384163314612fe85760808416612e83575b5050505050565b612f5c612f19612f5687612abd6040956280000098612f4262ffffff9989519788967f575e24b40000000000000000000000000000000000000000000000000000000060208901523360248901526044880190608090816001600160a01b039182815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b8051151560e48701526020810151610104870152604001516001600160a01b0316610124860152565b610140610144850152610164840191612591565b856131a6565b9401511614612fdc575b600816612f77575b80808080612e7c565b604001519250608083901d600f0b8015612f6e57612f98905f861295612626565b9315612fd4575f84135b612fac575f612f6e565b7ffa0b71d6000000000000000000000000000000000000000000000000000000005f5260045ffd5b5f8412612fa2565b60608201519350612f66565b505f965086955050505050565b90600f0b90600f0b01906f7fffffffffffffffffffffffffffffff1982126f7fffffffffffffffffffffffffffffff83131761177157565b919695939492946001600160a01b0383163314613199578460801d94600f0b9388604085166130cd575b50505050505f9481600f0b158015906130c1575b613077575b5050509190565b6130a59395505f60208201511290511515145f146130ad576001600160801b03169060801b175b80936138ce565b5f8080613070565b906001600160801b03169060801b1761309e565b5082600f0b151561306b565b61317d61318994612abd6113bb9561318f999895613162612f19966040519788967fb47b2fb10000000000000000000000000000000000000000000000000000000060208901523360248901526044880190608090816001600160a01b039182815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b8c610144850152610160610164850152610184840191612591565b600482161515916138b7565b90612ff5565b5f80808088613057565b5050505050909150905f90565b5f80939281926020825192019586915af1156132315760405191601f19603f3d011683016040523d83523d60208401905f823e51907fffffffff000000000000000000000000000000000000000000000000000000008091511691160361320957565b7f1e048e1d000000000000000000000000000000000000000000000000000000005f5260045ffd5b3d1561323f573d5f803e3d5ffd5b6336bc48c55f526004601cfd5b908160801b90600160801b5f19818509938380861095039480860395868511156102e057146132c5579082910981805f0316809204600280826003021880830282030280830282030280830282030280830282030280830282030280920290030293600183805f03040190848311900302920304170290565b505091500490565b81810291905f19828209918380841093039183830393600160801b93858511156102e05714613309570990828211900360801b910360801c1790565b5050505060801c90565b81810291905f19828209918380841093039183830393600160601b93858511156102e0571461334f570990828211900360a01b910360601c1790565b5050505060601c90565b90808202905f19818409908280831092039082820392620f424092848411156102e057146133b7577fde8f6cefed634549b62c77574f722e1ac57e23f24d8fd5cb790fb65668c26139940990828211900360fa1b910360061c170290565b509250500490565b908160601b90600160601b5f19818509938380861095039480860395868511156102e057146132c5579082910981805f0316809204600280826003021880830282030280830282030280830282030280830282030280830282030280920290030293600183805f03040190848311900302920304170290565b91818302915f19818509938380861095039480860395868511156102e057146132c5579082910981805f0316809204600280826003021880830282030280830282030280830282030280830282030280830282030280920290030293600183805f03040190848311900302920304170290565b91908181076134d15705908160081d5f52602052600160ff60405f2092161b8154189055565b63d4d8f3e65f526020526040526044601cfd5b8060ff1d81810118620d89e881116137f15763ffffffff91600182167001fffcb933bd6fad37aa2d162d1a59400102600160801b1891600281166137d5575b600481166137b9575b6008811661379d575b60108116613781575b60208116613765575b60408116613749575b60809081811661372e575b6101008116613713575b61020081166136f8575b61040081166136dd575b61080081166136c2575b61100081166136a7575b612000811661368c575b6140008116613671575b6180008116613656575b62010000811661363b575b620200008116613621575b620400008116613607575b62080000166135ed575b505f126135e5575b0160201c90565b5f19046135de565b6b048a170391f7dc42444e8fa25f929302901c91906135d6565b6d2216e584f5fa1ea926041bedfe98909302811c926135cc565b926e5d6af8dedb81196699c329225ee60402811c926135c1565b926f09aa508b5b7a84e1c677de54f3e99bc902811c926135b6565b926f31be135f97d08fd981231505542fcfa602811c926135ab565b926f70d869a156d2a1b890bb3df62baf32f702811c926135a1565b926fa9f746462d870fdf8a65dc1f90e061e502811c92613597565b926fd097f3bdfd2022b8845ad8f792aa582502811c9261358d565b926fe7159475a2c29b7443b29c7fa6e889d902811c92613583565b926ff3392b0822b70005940c7a398e4b70f302811c92613579565b926ff987a7253ac413176f2b074cf7815e5402811c9261356f565b926ffcbe86c7900a88aedcffc83b479aa3a402811c92613565565b926ffe5dee046a99a2a811c461f1969c305302811c9261355b565b916fff2ea16466c96a3843ec78b326b528610260801c91613550565b916fff973b41fa98c081472e6896dfb254c00260801c91613547565b916fffcb9843d60f6159c9db58835c9266440260801c9161353e565b916fffe5caca7e10e4e61c3624eaa0941cd00260801c91613535565b916ffff2e50f5f656932ef12357cf3c7fdcc0260801c9161352c565b916ffff97272373d413259a46990580e213a0260801c91613523565b63ce8ef7fc5f526004601cfd5b5f83600f0b125f14613832579161382d9161285493038060ff1d90810118905f036001600160801b0316613313565b614900565b90600160601b600191613867946001600160801b031693038060ff1d9081011861385c8185613313565b930915151601614900565b5f0390565b915f81600f0b125f14613893579161382d91612854935f036001600160801b03169161496e565b9161382d91613867936001600160801b031691614915565b01908160801c61261957565b906138c1916131a6565b9015612c2b576040015190565b6138f1906138e38360801d8260801d03612964565b92600f0b90600f0b03612964565b6001600160801b03169060801b1790565b73fffd8963efd1fc6a506488495d951d51639616826401000276a219820111613baa576001600160a01b0377ffffffffffffffffffffffffffffffffffffffff000000008260201b16806001600160801b03811160071b9181831c9267ffffffffffffffff841160061b93841c9363ffffffff851160051b94851c9461ffff861160041b95861c60ff9687821160031b91821c92600f841160021b93841c94600160038711811b96871c1196171717171717179160808310155f14613b9e5750607e1982011c5b8002607f928392828493841c81841c1c800280851c81851c1c800280861c81861c1c800280871c81871c1c80029081881c82881c1c80029283891c84891c1c800294858a1c868a1c1c800296878b1c888b1c1c800298898c1c8a8c1c1c80029a8b8d1c8c821c1c8002809d1c8d821c1c8002809e81901c90821c1c80029e8f80911c911c1c800260cd1c6604000000000000169d60cc1c6608000000000000169c60cb1c6610000000000000169b60ca1c6620000000000000169a60c91c6640000000000000169960c81c6680000000000000169860c71c670100000000000000169760c61c670200000000000000169660c51c670400000000000000169560c41c670800000000000000169460c31c671000000000000000169360c21c672000000000000000169260c11c674000000000000000169160c01c6780000000000000001690607f190160401b1717171717171717171717171717693627a301d71055774c8502907ffffffffffffffffffffffffffffffffffd709b7e5480fba5a50fed5e62ffc556820160801d60020b916fdb2df09e81959a81455e260799a0632f0160801d60020b928383145f14613b83575050905090565b811690613b8f846134e4565b1611613b99575090565b905090565b905081607f031b6139c9565b6331efafe85f526004601cfd5b8115613bc1570490565b634e487b7160e01b5f52601260045260245ffd5b915f9260405191613be583612375565b5f83525f60208401525f60408401525f60608401525f60808401525f60a08401528294825493602086015115956001600160801b0360038601541687155f146148f257610fff8760b81c16945b60408301518452876001600160a01b031660408501528760a01c60020b606085015288155f146148e85760018701545b60808501528160a0850152608083015162400000811615155f146148d95762bfffff16613c8e81612889565b61ffff87166148b9575b80925f604086015112918215968780986148a8575b6148805760408701511561486a5750508a61481d57606085016001600160a01b038151168b6001600160a01b03168110156147e55750516001600160a01b03166401000276a38111156147ba57505b604051998a60e081011067ffffffffffffffff60e08d0111176106ca5760e08b016040525f8b525f60208c01525f60408c01525f60608c01525f60808c01525f60a08c01525f60c08c01525b8c51158d8115614796575b50614697576001600160a01b0360408e0151168b5260608d015160020b865160020b8d155f14614539575f818307811382840503600881901d600190810b835260058f0160205260409092205460ff919091169190911b80015f190116801580159391908061451557815f916102e05782600160801b60ff941015614506575b50806801000000000000000060029210156144f8575b6401000000008110156144ea575b620100008110156144dc575b6101008110156144ce575b60108110156144c0575b60048110156144b3575b10156144a9575b815f858507128585050316031660020b90825f818307129105030360020b0260020b5b905b151560408d015260020b8060208d0152620d89e7198091131561449e575b50620d89e88060208d015160020b1215614493575b508c8c8c876001600160a01b03613e9e602084015160020b6134e4565b16918260608201526001600160a01b036040860151166001600160a01b0360608d0151169060a08701516001600160801b0381169662ffffff89519616906001600160a01b038115868a1018868a1802861816841015945f88125f1461431357620f424098838a0392613f13848b5f03613359565b9988156142df57613f308d89841587871018878718028718614915565b9a5b8b811061422557505082901581831018911802189782145f14614216575050845b925b15614194575091608091613f806040978796956001600160a01b0398038060ff1d9081011890613313565b905b60c083015260a08201520152169101528a8d881561415757602090613faa60a0840151614900565b815103815201613fc961382d82519360c0608082015191015190612503565b915f838203931281841281169184139015161761177157525b61ffff891661412d575b8c6001600160801b0360a0820151168c8161410d575b8e91508c6001600160a01b036040850151166001600160a01b0360608401511681145f146140d95750606092602091604084015161404f575b501591015160020b0360020b910152613d48565b6140b06001600160801b039183155f146140c65760808801519060046002820154915b8789015160020b5f5201865260405f2091600183019081549003905560028201908154900390555460801d83156140bc575b8260a0890151166138ab565b1660a08601528e61403b565b5f03600f0b6140a4565b600181015490600460808a015191614072565b9250506001600160a01b0390511681036140f5575b5050613d48565b614100606091613902565b60020b9101528c5f6140ee565b60809160c061411d92015161324c565b91019081510190528c5f8c614002565b9660808b015190620f424060c08d0151928361ffff8d169101020480920360c08d01520196613fec565b50608061416b91015160c08d015101614900565b8d51018d5260208d0161418d8c61418760a08451920151614900565b90612626565b9052613fe2565b95509392918391856001600160a01b0386168111614209575b5085156141fd576141f8866001600160a01b036141f08660409b6fffffffffffffffffffffffffffffffff60601b84809d8160809c169403169160601b16613438565b911690613bb7565b613f80565b62bfc9215f526004601cfd5b949550859492505f6141ad565b61422091876149c1565b613f53565b969b509950505050505086158215176142d257821561429057614249908783614a49565b945b85878385156142685761425d92614915565b8095015f0392613f55565b9050038060ff1d908101186001600160601b614284838b613313565b928a091515160161425d565b6142be906142b990886001600160a01b0382116142c4576142b39160601b613bb7565b83612503565b614ac7565b9461424b565b6142cd916133bf565b6142b3565b634f2461b85f526004601cfd5b8c6001600160601b8415878710188787180287188b038060ff1d908101186143078185613313565b9309151516019a613f32565b9198949795969591925087156144775761434284821585851018858518028518038060ff1d9081011886613313565b955b8681106143bb5750936001600160a01b039796938361438f9360409b989560809815818310189118021880985b1561439457906143819291614915565b809580620f424003916149c1565b613f82565b600160601b90600192038060ff1d908101186143b08185613313565b930915151601614381565b989550505050909392858515808415176142d2578515614454576001600160a01b038211614425575060601b858082061515910401955b868311156144185761438f6001600160a01b0396848860409a60809703165b8098614371565b634323a5555f526004601cfd5b9061443087826133bf565b91613bc157600160601b879109614448575b956143f2565b60010180614442575f80fd5b509561438f868461447260409a6001600160a01b039a6080986149ea565b614411565b61448d858215858510188585180285188661496e565b95614344565b60208c01525f613e81565b60208c01525f613e6c565b6001018116613e29565b918101831691811c613e22565b60049283018416921c613e18565b60089283018416921c613e0e565b60109283018416921c613e03565b60209283018416921c613df7565b60409283018416921c613de9565b60809250821c90506002613dd3565b50505f82820712908290050360ff8116600290810b909103810b909102900b613e4c565b9080825f81600194071291050301908160020b60081d60010b5f5260058c016020525f19600160ff84161b011960405f2054169182151592835f1461467a578081156102e05760ff9182906001600160801b03811615614670575050607f5b67ffffffffffffffff82161561466657603f190182165b63ffffffff82161561465c57601f190182165b61ffff82161561465257600f190182165b81831615614648576007190182165b600f82161561463e576003190182165b600382161561463257600119018216906001905b16614628575b82821690031660020b9060020b0160020b0260020b5b90613e4e565b5f1901811661460c565b9060019060021c614606565b9060041c906145f2565b9060081c906145e2565b9060101c906145d3565b9060201c906145c2565b9060401c906145af565b60801c9150614598565b5060ff81811681031660020b9060020b0160020b0260020b614622565b929b9894975092985094989350606087015160a01b62ffffff60a01b167fffffffffffffffffff00000000000000000000000000000000000000000000006001600160a01b0360408a0151169216171782556001600160801b0360a087015116809103614772575b50811561476357600260808601519101555b15146147465761473560406147296020850151612964565b92015183519003612964565b6001600160801b03169060801b1793565b6040015181516147569103612964565b6147356020830151612964565b60016080860151910155614711565b6fffffffffffffffffffffffffffffffff196003830154161760038201555f6146ff565b6001600160a01b03915060400151166001600160a01b03606088015116148d613d53565b7f9e4d7cc7000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b8b7f7c9c6e8f000000000000000000000000000000000000000000000000000000005f526001600160a01b031660045260245260445ffd5b606085016001600160a01b038151168b6001600160a01b03168111156147e55750516001600160a01b031673fffd8963efd1fc6a506488495d951d5263988d268110156147ba5750613cfc565b9a509a50505098505050505050505f925f929190565b7f96206246000000000000000000000000000000000000000000000000000000005f5260045ffd5b50620f424062ffffff831614613cad565b8061ffff881602620f424080820615159104019061ffff88160103613c98565b508760d01c62ffffff16613c8e565b6002870154613c62565b610fff8760c41c1694613c32565b5f811215612854576393dafdf15f526004601cfd5b916001600160a01b039182811683851611614968575b83156141fd5761495b916fffffffffffffffffffffffffffffffff60601b84868185169403169160601b166149c1565b9116808206151591040190565b9261492b565b90916001600160a01b0390818416828416116149b9575b82156141fd57836141f0916fffffffffffffffffffffffffffffffff60601b84868161285499169403169160601b16613438565b919291614985565b9291906149cf828286613438565b938215613bc157096149dd57565b906001019081156102e057565b908215614a43576fffffffffffffffffffffffffffffffff60601b9060601b166001600160a01b0382169283810292838311918404141615614a3657612854926142b9928203916149c1565b63f5c787f15f526004601cfd5b50905090565b91908115614ac2576fffffffffffffffffffffffffffffffff60601b9060601b16906001600160a01b0380931680820281614a848483613bb7565b14614aaa575b5090614a99614a9e9284613bb7565b612503565b80820615159104011690565b8301838110614a8a579150614abe926149c1565b1690565b505090565b74010000000000000000000000000000000000000000811015612619576001600160a01b03169056fea26469706673582212203b42a95f9efee278451fec8df069722b950534e5e5599295cc1b1aad571d1ba664736f6c63430008180033000000000000000000000000000000000000000000000000000000000007a120
Deployed Bytecode
0x6080806040526004361015610012575f80fd5b5f3560e01c908162fdd58e146122c45750806301ffc9a71461222357806307eff0dd14612208578063095bcdb61461216b5780630b0d9c09146120fb578063156e29f6146120575780631e2eaeaf1461203b578063234266d714611e195780632d77138914611d9957806335fd631a14611d48578063426a849314611cd357806348c8949114611af55780635275965114611a1f578063558a729714611994578063598af9e71461193a5780635a6bcfda1461100e57806360460f0614610ff2578063695c5bf514610b825780636a256b2914610a6a5780637e87ce7d1461097a5780638161b874146108d65780638da5cb5b146108b157806397e8cd4e146108795780639bf6645f14610843578063a584119414610820578063b6363cf2146107cd578063dbd035ff14610797578063f02de3b214610771578063f135baaa14610755578063f2fde38b146106de578063f3cd914c14610443578063f5298aca146102e45763fe99049a14610186575f80fd5b346102e05760803660031901126102e05761019f612303565b6101a7612319565b90604435917f1b3d7edb2e9c0b0e7c525b20aaaef0f5940d2ed71663c7d39266ecafac72885961024f606435936001600160a01b038091169384331415806102bf575b61025d575b845f52600460205260405f20875f5260205260405f206102108782546124f6565b90551693845f52600460205260405f20865f5260205260405f20610235828254612503565b905560408051338152602081019290925290918291820190565b0390a4602060405160018152f35b845f5260206005815260405f20335f52815260405f20885f52815260405f2054875f19820361028f575b5050506101ef565b610298916124f6565b90865f526005815260405f20335f52815260405f2090895f525260405f20555f8087610287565b50845f52600360205260405f20335f5260205260ff60405f205416156101ea565b5f80fd5b346102e0576102f23661232f565b7fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab239291925c1561041b577f1b3d7edb2e9c0b0e7c525b20aaaef0f5940d2ed71663c7d39266ecafac7288596103935f936001600160a01b0390610361610357866125fb565b3390848a16612641565b169233841415806103fa575b610398575b838552600460205260408520868652602052604085206102358282546124f6565b0390a4005b838552602060058152604086203387528152604086208787528152604086205482871982036103ca575b505050610372565b6103d3916124f6565b908587526005815260408720338852815260408720908888525260408620558680826103c2565b5083855260036020526040852033865260205260ff6040862054161561036d565b7f54e3ca0d000000000000000000000000000000000000000000000000000000005f5260045ffd5b346102e0576101203660031901126102e05761045e366123e1565b60603660a31901126102e0576040519067ffffffffffffffff60608301818111848210176106ca5760405260a43580151581036102e0578352602083019060c435825260e4356001600160a01b03811681036102e0576040850152610104359081116102e0576104d290369060040161245a565b917fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab235c1561041b57610502612746565b51156106a25782828261056b87847f40e9cecb9f5f1f1c5b9c97dec2917b7ee92e57ba5563708daca94dd84ad7112f60e062ffffff6105c4816001600160a01b0360209f61064f9e61063d9e6105779260a08b209a8b5f5260206006905260405f209d8e6127a0565b85608082015116612e55565b8a8f9395929f60600151958560408351151593015116916040519761059b89612391565b60020b885260208801526040870152606086015216608084015288511561069757511697613bd5565b939298829192610676575b50506001600160a01b036040840151169260606001600160801b0360a08301511691015160020b90604051943386528a60801d600f0b60208701528a600f0b60408701526060860152608085015260a08401521660c0820152a2876001600160a01b0360808201511661302d565b80939193610657575b50823391612857565b604051908152f35b610670906001600160a01b036080840151169083612857565b84610646565b6001600160a01b03165f528f6001905260405f209081540190558f806105cf565b602001511697613bd5565b7fbe8b8507000000000000000000000000000000000000000000000000000000005f5260045ffd5b634e487b7160e01b5f52604160045260245ffd5b346102e05760203660031901126102e05773ffffffffffffffffffffffffffffffffffffffff1961070d612303565b5f54906001600160a01b03906107268284163314612510565b1691829116175f55337f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f80a3005b346102e05760203660031901126102e0576004355c5f5260205ff35b346102e0575f3660031901126102e05760206001600160a01b0360025416604051908152f35b346102e0576107a5366124a9565b604060045f3760051b604001809160405b8135548152602091820191018281106107b657825ff35b346102e05760403660031901126102e0576107e6612303565b6107ee612319565b906001600160a01b038091165f52600360205260405f2091165f52602052602060ff60405f2054166040519015158152f35b346102e05760203660031901126102e057602061064f61083e612303565b6125b1565b346102e057610851366124a9565b604060045f3760051b604001809160405b81355c81526020918201910182811061086257825ff35b346102e05760203660031901126102e0576001600160a01b0361089a612303565b165f526001602052602060405f2054604051908152f35b346102e0575f3660031901126102e05760206001600160a01b035f5416604051908152f35b346102e05760603660031901126102e0576108ef612303565b6108f7612319565b6044356001600160a01b03806002541633036109525760209361064f928061094a57508184165f526001855260405f20549384925b81165f526001865260405f206109438482546124f6565b90556126d4565b93849261092c565b7f48f5c3ed000000000000000000000000000000000000000000000000000000005f5260045ffd5b346102e05760c03660031901126102e057610994366123e1565b61099c6123cf565b906001600160a01b0360025416330361095257623e900082106103e9610fff8416101615610a4257602060a07fe9c42593e71f84403b84352cd168d693e2c9fcd1fdbcc3feb21d92b43e6696f9922092835f526006825260405f20610a00816127a0565b805462ffffff60b81b8360b81b16907fffffffffffff000000ffffffffffffffffffffffffffffffffffffffffffffff1617905562ffffff60405191168152a2005b7fba97f838000000000000000000000000000000000000000000000000000000005f5260045ffd5b60203660031901126102e057610a7e612303565b7fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab235c1561041b576001600160a01b038116610acc5760209061064f34915b610ac5836125fb565b3391612641565b34610b5a577f1e0745a7db1623981f0b2a5d4232364c00787266eb75ad546f190e6cebe9bd955f528060205260405f205c908115610b32576020915f198114610b2b575b610b2561064f91610b20846125b1565b6124f6565b91610abc565b505f610b10565b7f8774be48000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f19d245cf000000000000000000000000000000000000000000000000000000005f5260045ffd5b346102e05760e03660031901126102e057610b9c366123e1565b6001600160a01b0360a4351660a435036102e05760c43567ffffffffffffffff81116102e057610bd090369060040161245a565b9091610bda612746565b617fff606082015160020b13610fca576001606082015160020b12610fa2576001600160a01b038151166001600160a01b036020830151161115610f7a576001600160a01b03608082015116610c3962ffffff60408401511682612b62565b15610f4f5750610c5162ffffff604083015116612c13565b9160808201516001600160a01b03811690813303610e7a575b505060a0822090610c7a83612c30565b959050825f52600660205260405f2080546001600160a01b0316610e525760209662ffffff60d01b610cad60a435613902565b9760d01b169062ffffff60b81b6001600160a01b0360a4351662ffffff60a01b8a60a01b16179160b81b16171790556080840151916001600160a01b0383163303610d74575b5050507f3fd553db44f207b1f41348cfc4d251860814af9eadc470e8e7895e4d120511f460806001600160a01b03845116926001600160a01b0387860151169462ffffff604082015116906001600160a01b0384606083015160020b92015116916040519384528984015260408301526060820152a36040519060020b8152f35b611000831615610cf357610e4992610e436001600160a01b0392610e356040519586927fa910f80f000000000000000000000000000000000000000000000000000000008d850152336024850152610e0d604485018c608090816001600160a01b039182815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b8660a4351660e48501528b60020b610104850152610120610124850152610144840191612591565b03601f1981018552846123ad565b166131a6565b50848080610cf3565b7f7983c051000000000000000000000000000000000000000000000000000000005f5260045ffd5b61200016610e89575b80610c6a565b610f4890604051907f3440d820000000000000000000000000000000000000000000000000000000006020830152336024830152610f086044830186608090816001600160a01b039182815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b6001600160a01b0360a4351660e4830152610100610104830152610f4382610f356101248201878b612591565b03601f1981018452836123ad565b6131a6565b5084610e83565b7fe65af6a0000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b7feaa6c6eb000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f16fe7696000000000000000000000000000000000000000000000000000000005f5260045ffd5b7fb02b5dc2000000000000000000000000000000000000000000000000000000005f5260045ffd5b346102e0575f3660031901126102e0576020604051617fff8152f35b346102e0576101403660031901126102e057611029366123e1565b60803660a31901126102e0576040519061104282612359565b60a4358060020b81036102e057825260c4358060020b81036102e057602083015260e43560408301526101043560608301526101243567ffffffffffffffff81116102e05761109590369060040161245a565b92907fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab235c1561041b576110c6612746565b60a0832093845f52600660205260405f20906110e1826127a0565b60808501516001600160a01b03811690813303611861575b5050835160020b92602085015160020b966111176040870151612964565b95606088015160020b9860608201516040519a6111338c612375565b338c528860208d01528260408d015289600f0b60608d015260808c015260a08b01525f908088121561183257620d89e719881261180657620d89e881136117db57604051986111818a612359565b5f8a525f60208b01525f60408b01525f60608b015280600f0b6115ad575b885f526004880160205260405f2098825f5260405f20895460a01c60020b8281125f1461155b575060028060018d0154600184015490039c015491015490039c5b60a06001600160a01b0382511691015160265283600652816003525f52603a600c205f6026525f526006890160205260405f209889549a83600f0b155f14611515576001600160801b038c16156114ed5761128060409f6113359c61127a916113479f5b60018301956112726001600160801b0360026112658286168b5486036132cd565b96019316835485036132cd565b9655556125fb565b916125fb565b6001600160801b03169060801b179b5f84600f0b12611483575b5082600f0b611372575b505050506112cb6112bc8960801d8360801d01612964565b9189600f0b90600f0b01612964565b6001600160801b03169060801b1791815160020b90602083015160020b8b840151908c5193845260208401528b8301527f541c041c2cce48e614b3de043c9280f06b6164c0a1741649e2de3c3d375f797460603393a3876001600160a01b03608082015116612a3b565b80949194611353575b50833391612857565b82519182526020820152f35b61136c906001600160a01b036080840151169083612857565b8561133e565b809192939450548060a01c60020b906001600160a01b0316908381125f146113cd57505050916113bb916113b56113ab6113c0956134e4565b91600f0b926134e4565b9061386c565b612964565b60801b5b8a8080806112a4565b948091939295125f14611458576113bb600393926113fe6113bb611411946113f889600f0b916134e4565b8761386c565b9361140c87600f0b926134e4565b6137fe565b6001600160801b03169060801b179201906fffffffffffffffffffffffffffffffff196001600160801b0361144d845493600f0b8285166138ab565b1691161790556113c4565b915061147593509161146f6113ab6113bb946134e4565b906137fe565b6001600160801b03166113c4565b808f91516114c3575b0151611499575b8e61129a565b6114be848260049160020b5f52016020525f6002604082208281558260018201550155565b611493565b6114e8848460049160020b5f52016020525f6002604082208281558260018201550155565b61148c565b7faefeb924000000000000000000000000000000000000000000000000000000005f5260045ffd5b61128060409f6113359c61127a916113479f6001600160801b0361153e8a600f0b8284166138ab565b166fffffffffffffffffffffffffffffffff198216178355611244565b909a9084136115815760028060018d0154600184015490039c015491015490039c6111e0565b99600260018b015460018d01549003600183015490039b81808d0154910154900391015490039c6111e0565b885f5260048801602052886001600160801b0360405f208054906115f3838316928d6115dc88600f0b866138ab565b9685156117ac575b505086600f0b9060801d612ff5565b60801b841790558c60208385169101521591161514158a52815f526004880160205260405f2080546001600160801b03811661163284600f0b826138ab565b928115611785575b6f7fffffffffffffffffffffffffffffff19600f86810b608086901d90910b039081126f7fffffffffffffffffffffffffffffff90911317611771576001600160801b039285600f0b9060801d600f0b0360801b841790558c606083851691015215911615141560408b0152898c5f83600f0b12156116f9575b50516116df575b60408a01511561119f576116da60808d015160020b8360058b016134ab565b61119f565b6116f460808d015160020b8a60058b016134ab565b6116bb565b60016001600160801b03602060808294015160020b94015116928080620d89e71905028180620d89e8050203050181041680911161175e576001600160801b0360608c0151161161174b57898c6116b4565b5063b8e3c38560e01b5f5260045260245ffd5b8963b8e3c38560e01b5f5260045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b8b5460a01c60020b861361163a5760018c0154600182015560028c0154600282015561163a565b815460a01c60020b12156117c1575b8f6115e4565b80600160029201546001860155015460028401558d6117bb565b7f1ad777f8000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b877fd5e2f7ab000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b877fc4433ed5000000000000000000000000000000000000000000000000000000005f5260045260245260445ffd5b5f60408701511380809161192d575b156118c25750506040517f259982e50000000000000000000000000000000000000000000000000000000060208201526118b991610f4382610f3586898b8d33602487016128c2565b505b86806110f9565b15908161191f575b506118d6575b506118bb565b6040517f21d0ee7000000000000000000000000000000000000000000000000000000000602082015261191891610f4382610f3586898b8d33602487016128c2565b50866118d0565b6102009150161515886118ca565b5061080082161515611870565b346102e05760603660031901126102e057611953612303565b61195b612319565b906001600160a01b038091165f52600560205260405f2091165f5260205260405f206044355f52602052602060405f2054604051908152f35b346102e05760403660031901126102e0576119ad612303565b6024358015158091036102e057335f5260036020526001600160a01b0360405f20921691825f5260205260405f2060ff1981541660ff83161790556040519081527fceb576d9f15e4e200fdb5096d64d5dfd667e16def20c1eefd14256d8e3faa26760203392a3602060405160018152f35b346102e05760c03660031901126102e057611a39366123e1565b611a416123cf565b906280000062ffffff60408301511614801590611ade575b611ab65760a090611a6983612889565b205f52600660205260405f2090611a7f826127a0565b81547fffffff000000ffffffffffffffffffffffffffffffffffffffffffffffffffff1660d09190911b62ffffff60d01b16179055005b7f30d21641000000000000000000000000000000000000000000000000000000005f5260045ffd5b506001600160a01b03608082015116331415611a59565b346102e0576020806003193601126102e05767ffffffffffffffff906004358281116102e057611b2990369060040161245a565b91907fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab2392835c611cab57611b98915f916001865d60405193849283927f91dd73460000000000000000000000000000000000000000000000000000000084528760048501526024840191612591565b038183335af1938415611ca0575f94611c2f575b50507f7d4b3164c6e45b97e7d87b7125a44c5828d005af88f9d751cfd78729c5d99a0b5c611c0757611bf9925f6040935d8251938285938452825192818480938701528686019101612488565b601f01601f19168101030190f35b7f5212cba1000000000000000000000000000000000000000000000000000000005f5260045ffd5b909193503d805f843e611c4281846123ad565b82019184818403126102e05780519182116102e0570181601f820112156102e0578051611c6e81612575565b92611c7c60405194856123ad565b8184528582840101116102e057611c9891858085019101612488565b918380611bac565b6040513d5f823e3d90fd5b7f5090d6c6000000000000000000000000000000000000000000000000000000005f5260045ffd5b346102e057611ce13661232f565b919091335f5260056020526001600160a01b0360405f20921691825f5260205260405f20835f526020528060405f20556040519081527fb3fd5071835887567a0671151121894ddccc2842f1d10bedad13e0d17cace9a760203392a4602060405160018152f35b346102e05760403660031901126102e05760043560209060205f5260243560051b8060205260400191829160018260405b835481520191019183821015611d955791906001908390611d79565b835ff35b346102e05760203660031901126102e0576004356001600160a01b038082168092036102e0577fb4bd8ef53df690b9943d3318996006dbb82a25f54719d8c8035b516a2a5b8acc91611df16020925f54163314612510565b8073ffffffffffffffffffffffffffffffffffffffff196002541617600255604051908152a1005b346102e0576101003660031901126102e057611e34366123e1565b60c43560a43560e43567ffffffffffffffff81116102e057611e5a90369060040161245a565b9190927fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab235c1561041b57611e8c612746565b60a085205f52600660205260405f2093611ea5856127a0565b60808601958651926001600160a01b039384811690813303611fe3575b50506001600160801b039788600389015416978815611fbb57602099611ee7886125fb565b5f0390611ef3856125fb565b5f03169060801b179887611fa2575b83611f87575b5050611f15338985612857565b5193841693843303611f2c575b8888604051908152f35b601016611f3a575b80611f22565b611f7b95610f4393610f35926040519788957fe1b4af69000000000000000000000000000000000000000000000000000000008d88015233602488016127d9565b50828080808080611f34565b611f936002918561324c565b91019081540190558980611f08565b611fac818961324c565b60018301908154019055611f02565b7fa74f97ab000000000000000000000000000000000000000000000000000000005f5260045ffd5b602016611ff1575b80611ec2565b6040517fb6a8b0fa00000000000000000000000000000000000000000000000000000000602082015261203491610f4382610f358b89888d8b33602488016127d9565b5088611feb565b346102e05760203660031901126102e057600435545f5260205ff35b346102e0576120653661232f565b90917fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab235c1561041b577f1b3d7edb2e9c0b0e7c525b20aaaef0f5940d2ed71663c7d39266ecafac7288596103935f926001600160a01b03906120d86120c9876125fb565b8603600f0b3390848a16612641565b169384845260046020526040842086855260205260408420610235828254612503565b346102e05760603660031901126102e057612114612303565b61211c612319565b604435907fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab235c1561041b5761216992612164612157846125fb565b5f03600f0b339083612641565b6126d4565b005b346102e0576001600160a01b036121813661232f565b91929092335f52600460205260405f20845f5260205260405f206121a68482546124f6565b90551690815f52600460205260405f20835f5260205260405f206121cb828254612503565b9055604080513380825260208201939093527f1b3d7edb2e9c0b0e7c525b20aaaef0f5940d2ed71663c7d39266ecafac728859918190810161024f565b346102e0575f3660031901126102e057602060405160018152f35b346102e05760203660031901126102e0576004357fffffffff0000000000000000000000000000000000000000000000000000000081168091036102e057807f01ffc9a7000000000000000000000000000000000000000000000000000000006020921490811561229a575b506040519015158152f35b7f0f632fb3000000000000000000000000000000000000000000000000000000009150148261228f565b346102e05760403660031901126102e0576020906001600160a01b036122e8612303565b165f526004825260405f206024355f52825260405f20548152f35b600435906001600160a01b03821682036102e057565b602435906001600160a01b03821682036102e057565b60609060031901126102e0576004356001600160a01b03811681036102e057906024359060443590565b6080810190811067ffffffffffffffff8211176106ca57604052565b60c0810190811067ffffffffffffffff8211176106ca57604052565b60a0810190811067ffffffffffffffff8211176106ca57604052565b90601f8019910116810190811067ffffffffffffffff8211176106ca57604052565b60a4359062ffffff821682036102e057565b60a09060031901126102e057604051906123fa82612391565b6001600160a01b038260043582811681036102e057815260243582811681036102e057602082015260443562ffffff811681036102e05760408201526064358060020b81036102e057606082015260843591821682036102e05760800152565b9181601f840112156102e05782359167ffffffffffffffff83116102e057602083818601950101116102e057565b5f5b8381106124995750505f910152565b818101518382015260200161248a565b9060206003198301126102e05760043567ffffffffffffffff928382116102e057806023830112156102e05781600401359384116102e05760248460051b830101116102e0576024019190565b9190820391821161177157565b9190820180921161177157565b1561251757565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600c60248201527f554e415554484f52495a454400000000000000000000000000000000000000006044820152fd5b67ffffffffffffffff81116106ca57601f01601f191660200190565b908060209392818452848401375f828201840152601f01601f1916010190565b906125bb82612dcb565b91829083156125f2575b7f1e0745a7db1623981f0b2a5d4232364c00787266eb75ad546f190e6cebe9bd955f5260205260405f205d565b5f1991506125c5565b6f8000000000000000000000000000000081101561261957600f0b90565b6393dafdf15f526004601cfd5b9190915f838201938412911290801582169115161761177157565b90600f0b9182156126cf57805f528160205261266260405f205c9384612626565b928361269e57507f7d4b3164c6e45b97e7d87b7125a44c5828d005af88f9d751cfd78729c5d99a0b805c5f1901905d5b5f5260205260405f205d565b612692577f7d4b3164c6e45b97e7d87b7125a44c5828d005af88f9d751cfd78729c5d99a0b6001815c01905d612692565b505050565b6001600160a01b0381166126ff57505f80809381935af1156126f257565b63f4b3b1bc5f526004601cfd5b60105f60449260209582956014526034526fa9059cbb00000000000000000000000082525af13d1560015f5114171615612739575f603452565b63f27f64e45f526004601cfd5b6001600160a01b037f0000000000000000000000005812baf38fb61d380c7863251deb496e1ed69a2e16300361277857565b7f0d89438e000000000000000000000000000000000000000000000000000000005f5260045ffd5b546001600160a01b0316156127b157565b7f486aa307000000000000000000000000000000000000000000000000000000005f5260045ffd5b919261283c612854979592946001600160a01b03610120961685526020850190608090816001600160a01b039182815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b60c083015260e0820152816101008201520191612591565b90565b90612887929160206001600160a01b039161287a85848351168660801d90612641565b01511690600f0b90612641565b565b62ffffff620f424091161161289a57565b7ffc5bee12000000000000000000000000000000000000000000000000000000005f5260045ffd5b90916128549593612927612956926001600160a01b03610160961685526020850190608090816001600160a01b039182815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b8051600290810b60c08501526020820151900b60e0840152604081015161010084015260600151610120830152565b816101408201520191612591565b806f800000000000000000000000000000000160801c1561298c576393dafdf15f526004601cfd5b600f0b90565b91612854969491936129f8612a27926001600160a01b03610180971686526020860190608090816001600160a01b039182815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b8051600290810b60c08601526020820151900b60e0850152604081015161010085015260600151610120840152565b610140820152816101608201520191612591565b929593945f956001600160a01b0385163314612b5857875f6040860151135f14612aea576104008616612a71575b505050505050565b612ade96989750612acb92612ad796959492612abd926040519687957f5a2a81000000000000000000000000000000000000000000000000000000000060208801523360248801612992565b03601f1981018352826123ad565b600282161515916138b7565b80926138ce565b915f8080808080612a69565b94939291906101008516612b0057505050505050565b612ade969850859750612b4c9291612abd91612ad7976040519687957f8db2b6520000000000000000000000000000000000000000000000000000000060208801523360248801612992565b600182161515916138b7565b505f955050505050565b608081161580612c07575b612bdd57604081161580612bfb575b612bdd5761040081161580612bef575b612bdd5761010081161580612be3575b612bdd576001600160a01b038116612bbd575062ffffff1662800000141590565b613fff161590811591612bce575090565b62800000915062ffffff161490565b50505f90565b50600181161515612b9c565b50600281161515612b8c565b50600481161515612b7c565b50600881161515612b6d565b6280000062ffffff821614612c2b5761285481612889565b505f90565b5f915f916001600160a01b03600254169081612c4a575050565b91935091505a7f000000000000000000000000000000000000000000000000000000000007a120809110612da35760405191612cef60208401917f553bfc370000000000000000000000000000000000000000000000000000000083526024850190608090816001600160a01b039182815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b60a4835260e0830183811067ffffffffffffffff8211176106ca575f94859485926040525193f13d15612d9b573d90612d2782612575565b91612d3560405193846123ad565b82523d5f602084013e5b158015612d90575b612d89576020015162ffffff8116908181149081612d71575b5015612d6b57600191565b505f8091565b90506103e9610fff623e90008410921610165f612d60565b505f905f90565b506020815111612d47565b606090612d3f565b7f1ee49702000000000000000000000000000000000000000000000000000000005f5260045ffd5b6001600160a01b031680612dde57504790565b6020602491604051928380927f70a082310000000000000000000000000000000000000000000000000000000082523060048301525afa908115611ca0575f91612e26575090565b90506020813d602011612e4d575b81612e41602093836123ad565b810103126102e0575190565b3d9150612e34565b949192945f945f946020810151976001600160a01b0384163314612fe85760808416612e83575b5050505050565b612f5c612f19612f5687612abd6040956280000098612f4262ffffff9989519788967f575e24b40000000000000000000000000000000000000000000000000000000060208901523360248901526044880190608090816001600160a01b039182815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b8051151560e48701526020810151610104870152604001516001600160a01b0316610124860152565b610140610144850152610164840191612591565b856131a6565b9401511614612fdc575b600816612f77575b80808080612e7c565b604001519250608083901d600f0b8015612f6e57612f98905f861295612626565b9315612fd4575f84135b612fac575f612f6e565b7ffa0b71d6000000000000000000000000000000000000000000000000000000005f5260045ffd5b5f8412612fa2565b60608201519350612f66565b505f965086955050505050565b90600f0b90600f0b01906f7fffffffffffffffffffffffffffffff1982126f7fffffffffffffffffffffffffffffff83131761177157565b919695939492946001600160a01b0383163314613199578460801d94600f0b9388604085166130cd575b50505050505f9481600f0b158015906130c1575b613077575b5050509190565b6130a59395505f60208201511290511515145f146130ad576001600160801b03169060801b175b80936138ce565b5f8080613070565b906001600160801b03169060801b1761309e565b5082600f0b151561306b565b61317d61318994612abd6113bb9561318f999895613162612f19966040519788967fb47b2fb10000000000000000000000000000000000000000000000000000000060208901523360248901526044880190608090816001600160a01b039182815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b8c610144850152610160610164850152610184840191612591565b600482161515916138b7565b90612ff5565b5f80808088613057565b5050505050909150905f90565b5f80939281926020825192019586915af1156132315760405191601f19603f3d011683016040523d83523d60208401905f823e51907fffffffff000000000000000000000000000000000000000000000000000000008091511691160361320957565b7f1e048e1d000000000000000000000000000000000000000000000000000000005f5260045ffd5b3d1561323f573d5f803e3d5ffd5b6336bc48c55f526004601cfd5b908160801b90600160801b5f19818509938380861095039480860395868511156102e057146132c5579082910981805f0316809204600280826003021880830282030280830282030280830282030280830282030280830282030280920290030293600183805f03040190848311900302920304170290565b505091500490565b81810291905f19828209918380841093039183830393600160801b93858511156102e05714613309570990828211900360801b910360801c1790565b5050505060801c90565b81810291905f19828209918380841093039183830393600160601b93858511156102e0571461334f570990828211900360a01b910360601c1790565b5050505060601c90565b90808202905f19818409908280831092039082820392620f424092848411156102e057146133b7577fde8f6cefed634549b62c77574f722e1ac57e23f24d8fd5cb790fb65668c26139940990828211900360fa1b910360061c170290565b509250500490565b908160601b90600160601b5f19818509938380861095039480860395868511156102e057146132c5579082910981805f0316809204600280826003021880830282030280830282030280830282030280830282030280830282030280920290030293600183805f03040190848311900302920304170290565b91818302915f19818509938380861095039480860395868511156102e057146132c5579082910981805f0316809204600280826003021880830282030280830282030280830282030280830282030280830282030280920290030293600183805f03040190848311900302920304170290565b91908181076134d15705908160081d5f52602052600160ff60405f2092161b8154189055565b63d4d8f3e65f526020526040526044601cfd5b8060ff1d81810118620d89e881116137f15763ffffffff91600182167001fffcb933bd6fad37aa2d162d1a59400102600160801b1891600281166137d5575b600481166137b9575b6008811661379d575b60108116613781575b60208116613765575b60408116613749575b60809081811661372e575b6101008116613713575b61020081166136f8575b61040081166136dd575b61080081166136c2575b61100081166136a7575b612000811661368c575b6140008116613671575b6180008116613656575b62010000811661363b575b620200008116613621575b620400008116613607575b62080000166135ed575b505f126135e5575b0160201c90565b5f19046135de565b6b048a170391f7dc42444e8fa25f929302901c91906135d6565b6d2216e584f5fa1ea926041bedfe98909302811c926135cc565b926e5d6af8dedb81196699c329225ee60402811c926135c1565b926f09aa508b5b7a84e1c677de54f3e99bc902811c926135b6565b926f31be135f97d08fd981231505542fcfa602811c926135ab565b926f70d869a156d2a1b890bb3df62baf32f702811c926135a1565b926fa9f746462d870fdf8a65dc1f90e061e502811c92613597565b926fd097f3bdfd2022b8845ad8f792aa582502811c9261358d565b926fe7159475a2c29b7443b29c7fa6e889d902811c92613583565b926ff3392b0822b70005940c7a398e4b70f302811c92613579565b926ff987a7253ac413176f2b074cf7815e5402811c9261356f565b926ffcbe86c7900a88aedcffc83b479aa3a402811c92613565565b926ffe5dee046a99a2a811c461f1969c305302811c9261355b565b916fff2ea16466c96a3843ec78b326b528610260801c91613550565b916fff973b41fa98c081472e6896dfb254c00260801c91613547565b916fffcb9843d60f6159c9db58835c9266440260801c9161353e565b916fffe5caca7e10e4e61c3624eaa0941cd00260801c91613535565b916ffff2e50f5f656932ef12357cf3c7fdcc0260801c9161352c565b916ffff97272373d413259a46990580e213a0260801c91613523565b63ce8ef7fc5f526004601cfd5b5f83600f0b125f14613832579161382d9161285493038060ff1d90810118905f036001600160801b0316613313565b614900565b90600160601b600191613867946001600160801b031693038060ff1d9081011861385c8185613313565b930915151601614900565b5f0390565b915f81600f0b125f14613893579161382d91612854935f036001600160801b03169161496e565b9161382d91613867936001600160801b031691614915565b01908160801c61261957565b906138c1916131a6565b9015612c2b576040015190565b6138f1906138e38360801d8260801d03612964565b92600f0b90600f0b03612964565b6001600160801b03169060801b1790565b73fffd8963efd1fc6a506488495d951d51639616826401000276a219820111613baa576001600160a01b0377ffffffffffffffffffffffffffffffffffffffff000000008260201b16806001600160801b03811160071b9181831c9267ffffffffffffffff841160061b93841c9363ffffffff851160051b94851c9461ffff861160041b95861c60ff9687821160031b91821c92600f841160021b93841c94600160038711811b96871c1196171717171717179160808310155f14613b9e5750607e1982011c5b8002607f928392828493841c81841c1c800280851c81851c1c800280861c81861c1c800280871c81871c1c80029081881c82881c1c80029283891c84891c1c800294858a1c868a1c1c800296878b1c888b1c1c800298898c1c8a8c1c1c80029a8b8d1c8c821c1c8002809d1c8d821c1c8002809e81901c90821c1c80029e8f80911c911c1c800260cd1c6604000000000000169d60cc1c6608000000000000169c60cb1c6610000000000000169b60ca1c6620000000000000169a60c91c6640000000000000169960c81c6680000000000000169860c71c670100000000000000169760c61c670200000000000000169660c51c670400000000000000169560c41c670800000000000000169460c31c671000000000000000169360c21c672000000000000000169260c11c674000000000000000169160c01c6780000000000000001690607f190160401b1717171717171717171717171717693627a301d71055774c8502907ffffffffffffffffffffffffffffffffffd709b7e5480fba5a50fed5e62ffc556820160801d60020b916fdb2df09e81959a81455e260799a0632f0160801d60020b928383145f14613b83575050905090565b811690613b8f846134e4565b1611613b99575090565b905090565b905081607f031b6139c9565b6331efafe85f526004601cfd5b8115613bc1570490565b634e487b7160e01b5f52601260045260245ffd5b915f9260405191613be583612375565b5f83525f60208401525f60408401525f60608401525f60808401525f60a08401528294825493602086015115956001600160801b0360038601541687155f146148f257610fff8760b81c16945b60408301518452876001600160a01b031660408501528760a01c60020b606085015288155f146148e85760018701545b60808501528160a0850152608083015162400000811615155f146148d95762bfffff16613c8e81612889565b61ffff87166148b9575b80925f604086015112918215968780986148a8575b6148805760408701511561486a5750508a61481d57606085016001600160a01b038151168b6001600160a01b03168110156147e55750516001600160a01b03166401000276a38111156147ba57505b604051998a60e081011067ffffffffffffffff60e08d0111176106ca5760e08b016040525f8b525f60208c01525f60408c01525f60608c01525f60808c01525f60a08c01525f60c08c01525b8c51158d8115614796575b50614697576001600160a01b0360408e0151168b5260608d015160020b865160020b8d155f14614539575f818307811382840503600881901d600190810b835260058f0160205260409092205460ff919091169190911b80015f190116801580159391908061451557815f916102e05782600160801b60ff941015614506575b50806801000000000000000060029210156144f8575b6401000000008110156144ea575b620100008110156144dc575b6101008110156144ce575b60108110156144c0575b60048110156144b3575b10156144a9575b815f858507128585050316031660020b90825f818307129105030360020b0260020b5b905b151560408d015260020b8060208d0152620d89e7198091131561449e575b50620d89e88060208d015160020b1215614493575b508c8c8c876001600160a01b03613e9e602084015160020b6134e4565b16918260608201526001600160a01b036040860151166001600160a01b0360608d0151169060a08701516001600160801b0381169662ffffff89519616906001600160a01b038115868a1018868a1802861816841015945f88125f1461431357620f424098838a0392613f13848b5f03613359565b9988156142df57613f308d89841587871018878718028718614915565b9a5b8b811061422557505082901581831018911802189782145f14614216575050845b925b15614194575091608091613f806040978796956001600160a01b0398038060ff1d9081011890613313565b905b60c083015260a08201520152169101528a8d881561415757602090613faa60a0840151614900565b815103815201613fc961382d82519360c0608082015191015190612503565b915f838203931281841281169184139015161761177157525b61ffff891661412d575b8c6001600160801b0360a0820151168c8161410d575b8e91508c6001600160a01b036040850151166001600160a01b0360608401511681145f146140d95750606092602091604084015161404f575b501591015160020b0360020b910152613d48565b6140b06001600160801b039183155f146140c65760808801519060046002820154915b8789015160020b5f5201865260405f2091600183019081549003905560028201908154900390555460801d83156140bc575b8260a0890151166138ab565b1660a08601528e61403b565b5f03600f0b6140a4565b600181015490600460808a015191614072565b9250506001600160a01b0390511681036140f5575b5050613d48565b614100606091613902565b60020b9101528c5f6140ee565b60809160c061411d92015161324c565b91019081510190528c5f8c614002565b9660808b015190620f424060c08d0151928361ffff8d169101020480920360c08d01520196613fec565b50608061416b91015160c08d015101614900565b8d51018d5260208d0161418d8c61418760a08451920151614900565b90612626565b9052613fe2565b95509392918391856001600160a01b0386168111614209575b5085156141fd576141f8866001600160a01b036141f08660409b6fffffffffffffffffffffffffffffffff60601b84809d8160809c169403169160601b16613438565b911690613bb7565b613f80565b62bfc9215f526004601cfd5b949550859492505f6141ad565b61422091876149c1565b613f53565b969b509950505050505086158215176142d257821561429057614249908783614a49565b945b85878385156142685761425d92614915565b8095015f0392613f55565b9050038060ff1d908101186001600160601b614284838b613313565b928a091515160161425d565b6142be906142b990886001600160a01b0382116142c4576142b39160601b613bb7565b83612503565b614ac7565b9461424b565b6142cd916133bf565b6142b3565b634f2461b85f526004601cfd5b8c6001600160601b8415878710188787180287188b038060ff1d908101186143078185613313565b9309151516019a613f32565b9198949795969591925087156144775761434284821585851018858518028518038060ff1d9081011886613313565b955b8681106143bb5750936001600160a01b039796938361438f9360409b989560809815818310189118021880985b1561439457906143819291614915565b809580620f424003916149c1565b613f82565b600160601b90600192038060ff1d908101186143b08185613313565b930915151601614381565b989550505050909392858515808415176142d2578515614454576001600160a01b038211614425575060601b858082061515910401955b868311156144185761438f6001600160a01b0396848860409a60809703165b8098614371565b634323a5555f526004601cfd5b9061443087826133bf565b91613bc157600160601b879109614448575b956143f2565b60010180614442575f80fd5b509561438f868461447260409a6001600160a01b039a6080986149ea565b614411565b61448d858215858510188585180285188661496e565b95614344565b60208c01525f613e81565b60208c01525f613e6c565b6001018116613e29565b918101831691811c613e22565b60049283018416921c613e18565b60089283018416921c613e0e565b60109283018416921c613e03565b60209283018416921c613df7565b60409283018416921c613de9565b60809250821c90506002613dd3565b50505f82820712908290050360ff8116600290810b909103810b909102900b613e4c565b9080825f81600194071291050301908160020b60081d60010b5f5260058c016020525f19600160ff84161b011960405f2054169182151592835f1461467a578081156102e05760ff9182906001600160801b03811615614670575050607f5b67ffffffffffffffff82161561466657603f190182165b63ffffffff82161561465c57601f190182165b61ffff82161561465257600f190182165b81831615614648576007190182165b600f82161561463e576003190182165b600382161561463257600119018216906001905b16614628575b82821690031660020b9060020b0160020b0260020b5b90613e4e565b5f1901811661460c565b9060019060021c614606565b9060041c906145f2565b9060081c906145e2565b9060101c906145d3565b9060201c906145c2565b9060401c906145af565b60801c9150614598565b5060ff81811681031660020b9060020b0160020b0260020b614622565b929b9894975092985094989350606087015160a01b62ffffff60a01b167fffffffffffffffffff00000000000000000000000000000000000000000000006001600160a01b0360408a0151169216171782556001600160801b0360a087015116809103614772575b50811561476357600260808601519101555b15146147465761473560406147296020850151612964565b92015183519003612964565b6001600160801b03169060801b1793565b6040015181516147569103612964565b6147356020830151612964565b60016080860151910155614711565b6fffffffffffffffffffffffffffffffff196003830154161760038201555f6146ff565b6001600160a01b03915060400151166001600160a01b03606088015116148d613d53565b7f9e4d7cc7000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b8b7f7c9c6e8f000000000000000000000000000000000000000000000000000000005f526001600160a01b031660045260245260445ffd5b606085016001600160a01b038151168b6001600160a01b03168111156147e55750516001600160a01b031673fffd8963efd1fc6a506488495d951d5263988d268110156147ba5750613cfc565b9a509a50505098505050505050505f925f929190565b7f96206246000000000000000000000000000000000000000000000000000000005f5260045ffd5b50620f424062ffffff831614613cad565b8061ffff881602620f424080820615159104019061ffff88160103613c98565b508760d01c62ffffff16613c8e565b6002870154613c62565b610fff8760c41c1694613c32565b5f811215612854576393dafdf15f526004601cfd5b916001600160a01b039182811683851611614968575b83156141fd5761495b916fffffffffffffffffffffffffffffffff60601b84868185169403169160601b166149c1565b9116808206151591040190565b9261492b565b90916001600160a01b0390818416828416116149b9575b82156141fd57836141f0916fffffffffffffffffffffffffffffffff60601b84868161285499169403169160601b16613438565b919291614985565b9291906149cf828286613438565b938215613bc157096149dd57565b906001019081156102e057565b908215614a43576fffffffffffffffffffffffffffffffff60601b9060601b166001600160a01b0382169283810292838311918404141615614a3657612854926142b9928203916149c1565b63f5c787f15f526004601cfd5b50905090565b91908115614ac2576fffffffffffffffffffffffffffffffff60601b9060601b16906001600160a01b0380931680820281614a848483613bb7565b14614aaa575b5090614a99614a9e9284613bb7565b612503565b80820615159104011690565b8301838110614a8a579150614abe926149c1565b1690565b505090565b74010000000000000000000000000000000000000000811015612619576001600160a01b03169056fea26469706673582212203b42a95f9efee278451fec8df069722b950534e5e5599295cc1b1aad571d1ba664736f6c63430008180033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
000000000000000000000000000000000000000000000000000000000007a120
-----Decoded View---------------
Arg [0] : controllerGasLimit (uint256): 500000
-----Encoded View---------------
1 Constructor Arguments found :
Arg [0] : 000000000000000000000000000000000000000000000000000000000007a120
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.