Verified contractPartialMIT
GweiFunFeeHook
Address0xb548791380e6dcdd1eef7259aeaeeb0900b86088
- Balance
0 ETH
- Transactions
2
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,443,858
- Creation transaction
- 0xebcac64fa3…669a2db70b
46 files
- src/platform/GweiFunFeeHook.solmain10.49 KB
- node_modules/@openzeppelin/contracts/access/Ownable.sol3.1 KB
- node_modules/@openzeppelin/contracts/access/Ownable2Step.sol2.48 KB
- node_modules/@openzeppelin/contracts/utils/Context.sol963 B
- node_modules/@openzeppelin/contracts/utils/ReentrancyGuard.sol3.38 KB
- node_modules/@uniswap/v4-periphery/lib/permit2/src/interfaces/IAllowanceTransfer.sol7.7 KB
- node_modules/@uniswap/v4-periphery/lib/permit2/src/interfaces/IEIP712.sol144 B
- node_modules/@uniswap/v4-periphery/lib/v4-core/src/interfaces/IExtsload.sol1.02 KB
- node_modules/@uniswap/v4-periphery/lib/v4-core/src/interfaces/IExttload.sol699 B
- node_modules/@uniswap/v4-periphery/lib/v4-core/src/interfaces/IHooks.sol8.23 KB
- node_modules/@uniswap/v4-periphery/lib/v4-core/src/interfaces/IPoolManager.sol12.84 KB
- node_modules/@uniswap/v4-periphery/lib/v4-core/src/interfaces/IProtocolFees.sol2.49 KB
- node_modules/@uniswap/v4-periphery/lib/v4-core/src/interfaces/callback/IUnlockCallback.sol488 B
- node_modules/@uniswap/v4-periphery/lib/v4-core/src/interfaces/external/IERC20Minimal.sol3.04 KB
- node_modules/@uniswap/v4-periphery/lib/v4-core/src/interfaces/external/IERC6909Claims.sol3.16 KB
- node_modules/@uniswap/v4-periphery/lib/v4-core/src/libraries/CustomRevert.sol5.17 KB
- node_modules/@uniswap/v4-periphery/lib/v4-core/src/libraries/Hooks.sol16.51 KB
- node_modules/@uniswap/v4-periphery/lib/v4-core/src/libraries/LPFeeLibrary.sol3.6 KB
- node_modules/@uniswap/v4-periphery/lib/v4-core/src/libraries/ParseBytes.sol1.2 KB
- node_modules/@uniswap/v4-periphery/lib/v4-core/src/libraries/SafeCast.sol2.27 KB
- node_modules/@uniswap/v4-periphery/lib/v4-core/src/types/BalanceDelta.sol2.34 KB
- node_modules/@uniswap/v4-periphery/lib/v4-core/src/types/BeforeSwapDelta.sol1.47 KB
- node_modules/@uniswap/v4-periphery/lib/v4-core/src/types/Currency.sol5.46 KB
- node_modules/@uniswap/v4-periphery/lib/v4-core/src/types/PoolId.sol539 B
- node_modules/@uniswap/v4-periphery/lib/v4-core/src/types/PoolKey.sol805 B
- node_modules/@uniswap/v4-periphery/lib/v4-core/src/types/PoolOperation.sol907 B
- node_modules/@uniswap/v4-periphery/src/base/ImmutableState.sol818 B
- node_modules/@uniswap/v4-periphery/src/interfaces/IEIP712_v4.sol328 B
- node_modules/@uniswap/v4-periphery/src/interfaces/IERC721Permit_v4.sol2.14 KB
- node_modules/@uniswap/v4-periphery/src/interfaces/IImmutableState.sol365 B
- node_modules/@uniswap/v4-periphery/src/interfaces/IMulticall_v4.sol774 B
- node_modules/@uniswap/v4-periphery/src/interfaces/INotifier.sol3.2 KB
- node_modules/@uniswap/v4-periphery/src/interfaces/IPermit2Forwarder.sol1.44 KB
- node_modules/@uniswap/v4-periphery/src/interfaces/IPoolInitializer_v4.sol782 B
- node_modules/@uniswap/v4-periphery/src/interfaces/IPositionManager.sol3.5 KB
- node_modules/@uniswap/v4-periphery/src/interfaces/ISubscriber.sol2.27 KB
- node_modules/@uniswap/v4-periphery/src/interfaces/IUnorderedNonce.sol799 B
- node_modules/@uniswap/v4-periphery/src/libraries/PositionInfoLibrary.sol3.95 KB
- node_modules/@uniswap/v4-periphery/src/utils/BaseHook.sol7.1 KB
- src/platform/hook/HookFeeMath.sol7.96 KB
- src/platform/hook/HookFeeVault.sol9.46 KB
- src/platform/hook/PoolFeeTerms.sol12.29 KB
- src/shared/GweiCreatorTag.sol4.87 KB
- src/shared/GweiFunVersion.sol4.92 KB
- src/shared/IGweiFunFeeHook.sol7.17 KB
- src/shared/IGweiFunLaunchpad.sol8.51 KB
src/platform/GweiFunFeeHook.sol
// SPDX-License-Identifier: MIT
/*
╔═══════════════════════════════════════════════════════════════════════════════════════╗
║ ▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚ ║
║ ▞ ▚ ║
║ ▞ ┌─[ SYS ]──────────────────────────────────────────────────────────[ v4 ]─┐ ▚ ║
║ ▞ │ ◉ ONLINE ◎ UNISWAP v4 ◎ ETHEREUM MAINNET ◎ PERMISSIONLESS LAUNCH │ ▚ ║
║ ▞ └─────────────────────────────────────────────────────────────────────────┘ ▚ ║
║ ▞ ▚ ║
║ ▞ ▄████████▄ ██ ██ ████████ ██ ████████ ██ ██ ███ ██ ▚ ║
║ ▞ ██▀▀▀▀▀▀▀▀ ██ ▄▄ ██ ██▀▀▀▀▀▀ ██ ██▀▀▀▀▀▀ ██ ██ ████▄ ██ ▚ ║
║ ▞ ██ ▄████▄ ██ ████ ██ ██████ ██ ██████ ██ ██ ██ ▀██▄██ ▚ ║
║ ▞ ██ ▀▀▀▀██ ██▀█▀▀█▀██ ██▄▄▄▄▄▄ ██ ▄▄ ██ ▀██▄▄██▀ ██ ▀███ ▚ ║
║ ▞ ▀████████▀ ▀██▀ ▀██▀ ████████ ██ ▀▀ ██ ▀████▀ ██ ▀██ ▚ ║
║ ▞ ▚ ║
║ ▞ ╭─────────────────────────────────────────────────────────────────────────╮ ▚ ║
║ ▞ │ ░▒▓█▓▒░ T O K E N L A U N C H P A D · H O O K P O W E R E D │ ▚ ║
║ ▞ ╰─────────────────────────────────────────────────────────────────────────╯ ▚ ║
║ ▞ ▚ ║
║ ▞ ┌──────────────────────────────────┐ ┌──────────────────────────────────┐ ▚ ║
║ ▞ │ ◈ https://gwei.fun/ │ │ ✕ https://x.com/gweidotfun │ ▚ ║
║ ▞ └──────────────────────────────────┘ └──────────────────────────────────┘ ▚ ║
║ ▞ ▚ ║
║ ▞ ·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──· ▚ ║
║ ▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚ ║
╚═══════════════════════════════════════════════════════════════════════════════════════╝
*/
pragma solidity 0.8.26;
import {BaseHook} from "@uniswap/v4-periphery/src/utils/BaseHook.sol";
import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.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 {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {SwapParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary, toBeforeSwapDelta} from "@uniswap/v4-core/src/types/BeforeSwapDelta.sol";
import {SafeCast} from "@uniswap/v4-core/src/libraries/SafeCast.sol";
import {GweiFunVersion} from "../shared/GweiFunVersion.sol";
import {IGweiFunLaunchpad} from "../shared/IGweiFunLaunchpad.sol";
import {FeeTerms} from "../shared/IGweiFunFeeHook.sol";
import {HookFeeMath} from "./hook/HookFeeMath.sol";
import {PoolFeeTerms} from "./hook/PoolFeeTerms.sol";
import {HookFeeVault} from "./hook/HookFeeVault.sol";
/// @title GweiFunFeeHook
/// @notice The one Uniswap v4 hook behind every pool the system opens.
///
/// Pools carry a zero LP fee; the whole swap charge is taken here, in `beforeSwap`, from the
/// swap's specified currency. An exact-input swap has the charge shaved off what reaches the
/// pool; an exact-output swap pays it on top and still receives the requested amount. The charge
/// is the protocol fee (shared between the creator's payee and the buyback side) plus the
/// creator's own buy/sell levy and a fading opening levy, never more than 10% together.
///
/// Liquidity is locked for good, so LP fees would be stranded in positions nobody can touch;
/// charging in the hook is what makes the revenue payable. See {HookFeeVault} for how it is held.
///
/// v4 derives hook permissions from the address, so deployment must land on an address whose low
/// bits equal {requiredHookFlags} (0x2088).
/// @custom:version 1.1
contract GweiFunFeeHook is GweiFunVersion, BaseHook, HookFeeVault {
string public constant launch = "disabled";
using PoolIdLibrary for PoolKey;
using SafeCast for uint256;
/// @param poolManager_ Uniswap v4 PoolManager.
/// @param launchpad_ Policy source.
/// @param owner_ Curates writers and exemptions.
constructor(IPoolManager poolManager_, IGweiFunLaunchpad launchpad_, address owner_)
BaseHook(poolManager_)
PoolFeeTerms(launchpad_, owner_)
{}
/// @dev Native currency arrives here when it is taken out of the PoolManager.
receive() external payable {}
/// @notice Flag bits the deployed address has to carry; single source for scripts and tests.
function requiredHookFlags() external pure returns (uint160) {
return Hooks.BEFORE_SWAP_RETURNS_DELTA_FLAG | Hooks.BEFORE_SWAP_FLAG | Hooks.BEFORE_INITIALIZE_FLAG;
}
/// @inheritdoc BaseHook
/// @dev beforeInitialize (1<<13) + beforeSwap (1<<7) + beforeSwapReturnDelta (1<<3) = 0x2088.
/// Liquidity and donate paths never reach this contract.
function getHookPermissions() public pure override returns (Hooks.Permissions memory granted) {
granted.beforeInitialize = true;
granted.beforeSwap = true;
granted.beforeSwapReturnDelta = true;
}
/// @inheritdoc BaseHook
/// @dev Only pools with stored terms may exist on this hook; otherwise anybody could open a
/// fee-free twin of a created token's market.
function _beforeInitialize(address, PoolKey calldata key, uint160) internal view override returns (bytes4) {
if (!_terms[key.toId()].active) revert UnknownPool();
return IHooks.beforeInitialize.selector;
}
/// @inheritdoc BaseHook
/// @dev Takes the charge as a positive specified-side BeforeSwapDelta and books an equal
/// ERC-6909 claim, so the PoolManager's accounts net to zero with no transfer.
function _beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata)
internal
override
returns (bytes4 selector, BeforeSwapDelta delta, uint24 feeOverride)
{
selector = IHooks.beforeSwap.selector;
delta = BeforeSwapDeltaLibrary.ZERO_DELTA;
feeOverride = 0;
PoolId poolId = key.toId();
FeeTerms storage terms = _terms[poolId];
if (!terms.active || isFeeExempt[sender]) return (selector, delta, feeOverride);
// Token is currency0: 0->1 sells it. Token is currency1: 0->1 buys it.
bool isBuy = terms.tokenIsZero != params.zeroForOne;
(uint256 allBips, uint256 protocolBips) = HookFeeMath.feeRates(terms, isBuy, block.timestamp);
if (allBips == 0) return (selector, delta, feeOverride);
(Currency charged, uint256 size) = _specifiedCurrencyAndAmount(key, params);
uint256 charge = HookFeeMath.feeAmount(size, allBips);
if (charge == 0) return (selector, delta, feeOverride);
(uint256 toPayee, uint256 toBuyback) = HookFeeMath.splitFee(charge, allBips, protocolBips, terms.creatorCutBips);
_accrue(terms.payee, charged, toPayee, toBuyback);
emit LevyTaken(poolId, charged, toPayee, toBuyback, isBuy);
delta = toBeforeSwapDelta(charge.toInt128(), 0);
}
/// @dev Specified currency and magnitude of a swap. Negative amount = exact input, where the
/// specified side is the input; otherwise it is the output.
function _specifiedCurrencyAndAmount(PoolKey calldata key, SwapParams calldata params)
private
pure
returns (Currency currency, uint256 size)
{
int256 raw = params.amountSpecified;
bool exactIn = raw < 0;
size = exactIn ? uint256(-raw) : uint256(raw);
currency = params.zeroForOne == exactIn ? key.currency0 : key.currency1;
}
}
node_modules/@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
node_modules/@openzeppelin/contracts/access/Ownable2Step.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*
* Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
node_modules/@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
node_modules/@openzeppelin/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
node_modules/@uniswap/v4-periphery/lib/permit2/src/interfaces/IAllowanceTransfer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IEIP712} from "./IEIP712.sol";
/// @title AllowanceTransfer
/// @notice Handles ERC20 token permissions through signature based allowance setting and ERC20 token transfers by checking allowed amounts
/// @dev Requires user's token approval on the Permit2 contract
interface IAllowanceTransfer is IEIP712 {
/// @notice Thrown when an allowance on a token has expired.
/// @param deadline The timestamp at which the allowed amount is no longer valid
error AllowanceExpired(uint256 deadline);
/// @notice Thrown when an allowance on a token has been depleted.
/// @param amount The maximum amount allowed
error InsufficientAllowance(uint256 amount);
/// @notice Thrown when too many nonces are invalidated.
error ExcessiveInvalidation();
/// @notice Emits an event when the owner successfully invalidates an ordered nonce.
event NonceInvalidation(
address indexed owner, address indexed token, address indexed spender, uint48 newNonce, uint48 oldNonce
);
/// @notice Emits an event when the owner successfully sets permissions on a token for the spender.
event Approval(
address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration
);
/// @notice Emits an event when the owner successfully sets permissions using a permit signature on a token for the spender.
event Permit(
address indexed owner,
address indexed token,
address indexed spender,
uint160 amount,
uint48 expiration,
uint48 nonce
);
/// @notice Emits an event when the owner sets the allowance back to 0 with the lockdown function.
event Lockdown(address indexed owner, address token, address spender);
/// @notice The permit data for a token
struct PermitDetails {
// ERC20 token address
address token;
// the maximum amount allowed to spend
uint160 amount;
// timestamp at which a spender's token allowances become invalid
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
/// @notice The permit message signed for a single token allowance
struct PermitSingle {
// the permit data for a single token alownce
PermitDetails details;
// address permissioned on the allowed tokens
address spender;
// deadline on the permit signature
uint256 sigDeadline;
}
/// @notice The permit message signed for multiple token allowances
struct PermitBatch {
// the permit data for multiple token allowances
PermitDetails[] details;
// address permissioned on the allowed tokens
address spender;
// deadline on the permit signature
uint256 sigDeadline;
}
/// @notice The saved permissions
/// @dev This info is saved per owner, per token, per spender and all signed over in the permit message
/// @dev Setting amount to type(uint160).max sets an unlimited approval
struct PackedAllowance {
// amount allowed
uint160 amount;
// permission expiry
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
/// @notice A token spender pair.
struct TokenSpenderPair {
// the token the spender is approved
address token;
// the spender address
address spender;
}
/// @notice Details for a token transfer.
struct AllowanceTransferDetails {
// the owner of the token
address from;
// the recipient of the token
address to;
// the amount of the token
uint160 amount;
// the token to be transferred
address token;
}
/// @notice A mapping from owner address to token address to spender address to PackedAllowance struct, which contains details and conditions of the approval.
/// @notice The mapping is indexed in the above order see: allowance[ownerAddress][tokenAddress][spenderAddress]
/// @dev The packed slot holds the allowed amount, expiration at which the allowed amount is no longer valid, and current nonce thats updated on any signature based approvals.
function allowance(address user, address token, address spender)
external
view
returns (uint160 amount, uint48 expiration, uint48 nonce);
/// @notice Approves the spender to use up to amount of the specified token up until the expiration
/// @param token The token to approve
/// @param spender The spender address to approve
/// @param amount The approved amount of the token
/// @param expiration The timestamp at which the approval is no longer valid
/// @dev The packed allowance also holds a nonce, which will stay unchanged in approve
/// @dev Setting amount to type(uint160).max sets an unlimited approval
function approve(address token, address spender, uint160 amount, uint48 expiration) external;
/// @notice Permit a spender to a given amount of the owners token via the owner's EIP-712 signature
/// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
/// @param owner The owner of the tokens being approved
/// @param permitSingle Data signed over by the owner specifying the terms of approval
/// @param signature The owner's signature over the permit data
function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external;
/// @notice Permit a spender to the signed amounts of the owners tokens via the owner's EIP-712 signature
/// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
/// @param owner The owner of the tokens being approved
/// @param permitBatch Data signed over by the owner specifying the terms of approval
/// @param signature The owner's signature over the permit data
function permit(address owner, PermitBatch memory permitBatch, bytes calldata signature) external;
/// @notice Transfer approved tokens from one address to another
/// @param from The address to transfer from
/// @param to The address of the recipient
/// @param amount The amount of the token to transfer
/// @param token The token address to transfer
/// @dev Requires the from address to have approved at least the desired amount
/// of tokens to msg.sender.
function transferFrom(address from, address to, uint160 amount, address token) external;
/// @notice Transfer approved tokens in a batch
/// @param transferDetails Array of owners, recipients, amounts, and tokens for the transfers
/// @dev Requires the from addresses to have approved at least the desired amount
/// of tokens to msg.sender.
function transferFrom(AllowanceTransferDetails[] calldata transferDetails) external;
/// @notice Enables performing a "lockdown" of the sender's Permit2 identity
/// by batch revoking approvals
/// @param approvals Array of approvals to revoke.
function lockdown(TokenSpenderPair[] calldata approvals) external;
/// @notice Invalidate nonces for a given (token, spender) pair
/// @param token The token to invalidate nonces for
/// @param spender The spender to invalidate nonces for
/// @param newNonce The new nonce to set. Invalidates all nonces less than it.
/// @dev Can't invalidate more than 2**16 nonces per transaction.
function invalidateNonces(address token, address spender, uint48 newNonce) external;
}
node_modules/@uniswap/v4-periphery/lib/permit2/src/interfaces/IEIP712.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IEIP712 {
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
node_modules/@uniswap/v4-periphery/lib/v4-core/src/interfaces/IExtsload.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for functions to access any storage slot in a contract
interface IExtsload {
/// @notice Called by external contracts to access granular pool state
/// @param slot Key of slot to sload
/// @return value The value of the slot as bytes32
function extsload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access granular pool state
/// @param startSlot Key of slot to start sloading from
/// @param nSlots Number of slots to load into return value
/// @return values List of loaded values.
function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);
/// @notice Called by external contracts to access sparse pool state
/// @param slots List of slots to SLOAD from.
/// @return values List of loaded values.
function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}
node_modules/@uniswap/v4-periphery/lib/v4-core/src/interfaces/IExttload.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @notice Interface for functions to access any transient storage slot in a contract
interface IExttload {
/// @notice Called by external contracts to access transient storage of the contract
/// @param slot Key of slot to tload
/// @return value The value of the slot as bytes32
function exttload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access sparse transient pool state
/// @param slots List of slots to tload
/// @return values List of loaded values
function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}
node_modules/@uniswap/v4-periphery/lib/v4-core/src/interfaces/IHooks.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";
/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
/// @notice The hook called before the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @return bytes4 The function selector for the hook
function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);
/// @notice The hook called after the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @param tick The current tick after the state of a pool is initialized
/// @return bytes4 The function selector for the hook
function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
external
returns (bytes4);
/// @notice The hook called before liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
/// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
external
returns (bytes4, BeforeSwapDelta, uint24);
/// @notice The hook called after a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterSwap(
address sender,
PoolKey calldata key,
SwapParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) external returns (bytes4, int128);
/// @notice The hook called before donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function afterDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
}
node_modules/@uniswap/v4-periphery/lib/v4-core/src/interfaces/IPoolManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {Currency} from "../types/Currency.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "./IHooks.sol";
import {IERC6909Claims} from "./external/IERC6909Claims.sol";
import {IProtocolFees} from "./IProtocolFees.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {PoolId} from "../types/PoolId.sol";
import {IExtsload} from "./IExtsload.sol";
import {IExttload} from "./IExttload.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
/// @notice Interface for the PoolManager
interface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {
/// @notice Thrown when a currency is not netted out after the contract is unlocked
error CurrencyNotSettled();
/// @notice Thrown when trying to interact with a non-initialized pool
error PoolNotInitialized();
/// @notice Thrown when unlock is called, but the contract is already unlocked
error AlreadyUnlocked();
/// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not
error ManagerLocked();
/// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow
error TickSpacingTooLarge(int24 tickSpacing);
/// @notice Pools must have a positive non-zero tickSpacing passed to #initialize
error TickSpacingTooSmall(int24 tickSpacing);
/// @notice PoolKey must have currencies where address(currency0) < address(currency1)
error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);
/// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,
/// or on a pool that does not have a dynamic swap fee.
error UnauthorizedDynamicLPFeeUpdate();
/// @notice Thrown when trying to swap amount of 0
error SwapAmountCannotBeZero();
///@notice Thrown when native currency is passed to a non native settlement
error NonzeroNativeValue();
/// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.
error MustClearExactPositiveDelta();
/// @notice Emitted when a new pool is initialized
/// @param id The abi encoded hash of the pool key struct for the new pool
/// @param currency0 The first currency of the pool by address sort order
/// @param currency1 The second currency of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param hooks The hooks contract address for the pool, or address(0) if none
/// @param sqrtPriceX96 The price of the pool on initialization
/// @param tick The initial tick of the pool corresponding to the initialized price
event Initialize(
PoolId indexed id,
Currency indexed currency0,
Currency indexed currency1,
uint24 fee,
int24 tickSpacing,
IHooks hooks,
uint160 sqrtPriceX96,
int24 tick
);
/// @notice Emitted when a liquidity position is modified
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that modified the pool
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param liquidityDelta The amount of liquidity that was added or removed
/// @param salt The extra data to make positions unique
event ModifyLiquidity(
PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt
);
/// @notice Emitted for swaps between currency0 and currency1
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that initiated the swap call, and that received the callback
/// @param amount0 The delta of the currency0 balance of the pool
/// @param amount1 The delta of the currency1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of the price of the pool after the swap
/// @param fee The swap fee in hundredths of a bip
event Swap(
PoolId indexed id,
address indexed sender,
int128 amount0,
int128 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick,
uint24 fee
);
/// @notice Emitted for donations
/// @param id The abi encoded hash of the pool key struct for the pool that was donated to
/// @param sender The address that initiated the donate call
/// @param amount0 The amount donated in currency0
/// @param amount1 The amount donated in currency1
event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);
/// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement
/// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.
/// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`
/// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`
/// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`
function unlock(bytes calldata data) external returns (bytes memory);
/// @notice Initialize the state for a given pool ID
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The pool key for the pool to initialize
/// @param sqrtPriceX96 The initial square root price
/// @return tick The initial tick of the pool
function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);
/// @notice Modify the liquidity for the given pool
/// @dev Poke by calling with a zero liquidityDelta
/// @param key The pool to modify liquidity in
/// @param params The parameters for modifying the liquidity
/// @param hookData The data to pass through to the add/removeLiquidity hooks
/// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable
/// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes
/// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value
/// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)
/// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
external
returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);
/// @notice Swap against the given pool
/// @param key The pool to swap in
/// @param params The parameters for swapping
/// @param hookData The data to pass through to the swap hooks
/// @return swapDelta The balance delta of the address swapping
/// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.
/// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG
/// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.
function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
external
returns (BalanceDelta swapDelta);
/// @notice Donate the given currency amounts to the in-range liquidity providers of a pool
/// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.
/// Donors should keep this in mind when designing donation mechanisms.
/// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of
/// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to
/// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).
/// Read the comments in `Pool.swap()` for more information about this.
/// @param key The key of the pool to donate to
/// @param amount0 The amount of currency0 to donate
/// @param amount1 The amount of currency1 to donate
/// @param hookData The data to pass through to the donate hooks
/// @return BalanceDelta The delta of the caller after the donate
function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
external
returns (BalanceDelta);
/// @notice Writes the current ERC20 balance of the specified currency to transient storage
/// This is used to checkpoint balances for the manager and derive deltas for the caller.
/// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped
/// for native tokens because the amount to settle is determined by the sent value.
/// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle
/// native funds, this function can be called with the native currency to then be able to settle the native currency
function sync(Currency currency) external;
/// @notice Called by the user to net out some value owed to the user
/// @dev Will revert if the requested amount is not available, consider using `mint` instead
/// @dev Can also be used as a mechanism for free flash loans
/// @param currency The currency to withdraw from the pool manager
/// @param to The address to withdraw to
/// @param amount The amount of currency to withdraw
function take(Currency currency, address to, uint256 amount) external;
/// @notice Called by the user to pay what is owed
/// @return paid The amount of currency settled
function settle() external payable returns (uint256 paid);
/// @notice Called by the user to pay on behalf of another address
/// @param recipient The address to credit for the payment
/// @return paid The amount of currency settled
function settleFor(address recipient) external payable returns (uint256 paid);
/// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.
/// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.
/// @dev This could be used to clear a balance that is considered dust.
/// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.
function clear(Currency currency, uint256 amount) external;
/// @notice Called by the user to move value into ERC6909 balance
/// @param to The address to mint the tokens to
/// @param id The currency address to mint to ERC6909s, as a uint256
/// @param amount The amount of currency to mint
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function mint(address to, uint256 id, uint256 amount) external;
/// @notice Called by the user to move value from ERC6909 balance
/// @param from The address to burn the tokens from
/// @param id The currency address to burn from ERC6909s, as a uint256
/// @param amount The amount of currency to burn
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function burn(address from, uint256 id, uint256 amount) external;
/// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The key of the pool to update dynamic LP fees for
/// @param newDynamicLPFee The new dynamic pool LP fee
function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;
}
node_modules/@uniswap/v4-periphery/lib/v4-core/src/interfaces/IProtocolFees.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "../types/Currency.sol";
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";
/// @notice Interface for all protocol-fee related functions in the pool manager
interface IProtocolFees {
/// @notice Thrown when protocol fee is set too high
error ProtocolFeeTooLarge(uint24 fee);
/// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.
error InvalidCaller();
/// @notice Thrown when collectProtocolFees is attempted on a token that is synced.
error ProtocolFeeCurrencySynced();
/// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.
event ProtocolFeeControllerUpdated(address indexed protocolFeeController);
/// @notice Emitted when the protocol fee is updated for a pool.
event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);
/// @notice Given a currency address, returns the protocol fees accrued in that currency
/// @param currency The currency to check
/// @return amount The amount of protocol fees accrued in the currency
function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);
/// @notice Sets the protocol fee for the given pool
/// @param key The key of the pool to set a protocol fee for
/// @param newProtocolFee The fee to set
function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;
/// @notice Sets the protocol fee controller
/// @param controller The new protocol fee controller
function setProtocolFeeController(address controller) external;
/// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected
/// @dev This will revert if the contract is unlocked
/// @param recipient The address to receive the protocol fees
/// @param currency The currency to withdraw
/// @param amount The amount of currency to withdraw
/// @return amountCollected The amount of currency successfully withdrawn
function collectProtocolFees(address recipient, Currency currency, uint256 amount)
external
returns (uint256 amountCollected);
/// @notice Returns the current protocol fee controller address
/// @return address The current protocol fee controller address
function protocolFeeController() external view returns (address);
}
node_modules/@uniswap/v4-periphery/lib/v4-core/src/interfaces/callback/IUnlockCallback.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for the callback executed when an address unlocks the pool manager
interface IUnlockCallback {
/// @notice Called by the pool manager on `msg.sender` when the manager is unlocked
/// @param data The data that was passed to the call to unlock
/// @return Any data that you want to be returned from the unlock call
function unlockCallback(bytes calldata data) external returns (bytes memory);
}
node_modules/@uniswap/v4-periphery/lib/v4-core/src/interfaces/external/IERC20Minimal.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
/// @notice Returns an account's balance in the token
/// @param account The account for which to look up the number of tokens it has, i.e. its balance
/// @return The number of tokens held by the account
function balanceOf(address account) external view returns (uint256);
/// @notice Transfers the amount of token from the `msg.sender` to the recipient
/// @param recipient The account that will receive the amount transferred
/// @param amount The number of tokens to send from the sender to the recipient
/// @return Returns true for a successful transfer, false for an unsuccessful transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/// @notice Returns the current allowance given to a spender by an owner
/// @param owner The account of the token owner
/// @param spender The account of the token spender
/// @return The current allowance granted by `owner` to `spender`
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
/// @param spender The account which will be allowed to spend a given amount of the owners tokens
/// @param amount The amount of tokens allowed to be used by `spender`
/// @return Returns true for a successful approval, false for unsuccessful
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
/// @param sender The account from which the transfer will be initiated
/// @param recipient The recipient of the transfer
/// @param amount The amount of the transfer
/// @return Returns true for a successful transfer, false for unsuccessful
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
/// @param from The account from which the tokens were sent, i.e. the balance decreased
/// @param to The account to which the tokens were sent, i.e. the balance increased
/// @param value The amount of tokens that were transferred
event Transfer(address indexed from, address indexed to, uint256 value);
/// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
/// @param owner The account that approved spending of its tokens
/// @param spender The account for which the spending allowance was modified
/// @param value The new allowance from the owner to the spender
event Approval(address indexed owner, address indexed spender, uint256 value);
}
node_modules/@uniswap/v4-periphery/lib/v4-core/src/interfaces/external/IERC6909Claims.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for claims over a contract balance, wrapped as a ERC6909
interface IERC6909Claims {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event OperatorSet(address indexed owner, address indexed operator, bool approved);
event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);
event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);
/*//////////////////////////////////////////////////////////////
FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Owner balance of an id.
/// @param owner The address of the owner.
/// @param id The id of the token.
/// @return amount The balance of the token.
function balanceOf(address owner, uint256 id) external view returns (uint256 amount);
/// @notice Spender allowance of an id.
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @return amount The allowance of the token.
function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);
/// @notice Checks if a spender is approved by an owner as an operator
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @return approved The approval status.
function isOperator(address owner, address spender) external view returns (bool approved);
/// @notice Transfers an amount of an id from the caller to a receiver.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Transfers an amount of an id from a sender to a receiver.
/// @param sender The address of the sender.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Approves an amount of an id to a spender.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always
function approve(address spender, uint256 id, uint256 amount) external returns (bool);
/// @notice Sets or removes an operator for the caller.
/// @param operator The address of the operator.
/// @param approved The approval status.
/// @return bool True, always
function setOperator(address operator, bool approved) external returns (bool);
}
node_modules/@uniswap/v4-periphery/lib/v4-core/src/libraries/CustomRevert.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
/// @dev Reverts with the selector of a custom error in the scratch space
function revertWith(bytes4 selector) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
revert(0, 0x04)
}
}
/// @dev Reverts with a custom error with an address argument in the scratch space
function revertWith(bytes4 selector, address addr) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with an int24 argument in the scratch space
function revertWith(bytes4 selector, int24 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, signextend(2, value))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with a uint160 argument in the scratch space
function revertWith(bytes4 selector, uint160 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with two int24 arguments
function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), signextend(2, value1))
mstore(add(fmp, 0x24), signextend(2, value2))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two uint160 arguments
function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two address arguments
function revertWith(bytes4 selector, address value1, address value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
/// @dev this method can be vulnerable to revert data bombs
function bubbleUpAndRevertWith(
address revertingContract,
bytes4 revertingFunctionSelector,
bytes4 additionalContext
) internal pure {
bytes4 wrappedErrorSelector = WrappedError.selector;
assembly ("memory-safe") {
// Ensure the size of the revert data is a multiple of 32 bytes
let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)
let fmp := mload(0x40)
// Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
mstore(fmp, wrappedErrorSelector)
mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(
add(fmp, 0x24),
and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
// offset revert reason
mstore(add(fmp, 0x44), 0x80)
// offset additional context
mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
// size revert reason
mstore(add(fmp, 0x84), returndatasize())
// revert reason
returndatacopy(add(fmp, 0xa4), 0, returndatasize())
// size additional context
mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
// additional context
mstore(
add(fmp, add(0xc4, encodedDataSize)),
and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
revert(fmp, add(0xe4, encodedDataSize))
}
}
}
node_modules/@uniswap/v4-periphery/lib/v4-core/src/libraries/Hooks.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {SafeCast} from "./SafeCast.sol";
import {LPFeeLibrary} from "./LPFeeLibrary.sol";
import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "../types/BeforeSwapDelta.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {ParseBytes} from "./ParseBytes.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
library Hooks {
using LPFeeLibrary for uint24;
using Hooks for IHooks;
using SafeCast for int256;
using BeforeSwapDeltaLibrary for BeforeSwapDelta;
using ParseBytes for bytes;
using CustomRevert for bytes4;
uint160 internal constant ALL_HOOK_MASK = uint160((1 << 14) - 1);
uint160 internal constant BEFORE_INITIALIZE_FLAG = 1 << 13;
uint160 internal constant AFTER_INITIALIZE_FLAG = 1 << 12;
uint160 internal constant BEFORE_ADD_LIQUIDITY_FLAG = 1 << 11;
uint160 internal constant AFTER_ADD_LIQUIDITY_FLAG = 1 << 10;
uint160 internal constant BEFORE_REMOVE_LIQUIDITY_FLAG = 1 << 9;
uint160 internal constant AFTER_REMOVE_LIQUIDITY_FLAG = 1 << 8;
uint160 internal constant BEFORE_SWAP_FLAG = 1 << 7;
uint160 internal constant AFTER_SWAP_FLAG = 1 << 6;
uint160 internal constant BEFORE_DONATE_FLAG = 1 << 5;
uint160 internal constant AFTER_DONATE_FLAG = 1 << 4;
uint160 internal constant BEFORE_SWAP_RETURNS_DELTA_FLAG = 1 << 3;
uint160 internal constant AFTER_SWAP_RETURNS_DELTA_FLAG = 1 << 2;
uint160 internal constant AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 1;
uint160 internal constant AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 0;
struct Permissions {
bool beforeInitialize;
bool afterInitialize;
bool beforeAddLiquidity;
bool afterAddLiquidity;
bool beforeRemoveLiquidity;
bool afterRemoveLiquidity;
bool beforeSwap;
bool afterSwap;
bool beforeDonate;
bool afterDonate;
bool beforeSwapReturnDelta;
bool afterSwapReturnDelta;
bool afterAddLiquidityReturnDelta;
bool afterRemoveLiquidityReturnDelta;
}
/// @notice Thrown if the address will not lead to the specified hook calls being called
/// @param hooks The address of the hooks contract
error HookAddressNotValid(address hooks);
/// @notice Hook did not return its selector
error InvalidHookResponse();
/// @notice Additional context for ERC-7751 wrapped error when a hook call fails
error HookCallFailed();
/// @notice The hook's delta changed the swap from exactIn to exactOut or vice versa
error HookDeltaExceedsSwapAmount();
/// @notice Utility function intended to be used in hook constructors to ensure
/// the deployed hooks address causes the intended hooks to be called
/// @param permissions The hooks that are intended to be called
/// @dev permissions param is memory as the function will be called from constructors
function validateHookPermissions(IHooks self, Permissions memory permissions) internal pure {
if (
permissions.beforeInitialize != self.hasPermission(BEFORE_INITIALIZE_FLAG)
|| permissions.afterInitialize != self.hasPermission(AFTER_INITIALIZE_FLAG)
|| permissions.beforeAddLiquidity != self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)
|| permissions.afterAddLiquidity != self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)
|| permissions.beforeRemoveLiquidity != self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)
|| permissions.afterRemoveLiquidity != self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
|| permissions.beforeSwap != self.hasPermission(BEFORE_SWAP_FLAG)
|| permissions.afterSwap != self.hasPermission(AFTER_SWAP_FLAG)
|| permissions.beforeDonate != self.hasPermission(BEFORE_DONATE_FLAG)
|| permissions.afterDonate != self.hasPermission(AFTER_DONATE_FLAG)
|| permissions.beforeSwapReturnDelta != self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)
|| permissions.afterSwapReturnDelta != self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
|| permissions.afterAddLiquidityReturnDelta != self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
|| permissions.afterRemoveLiquidityReturnDelta
!= self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
) {
HookAddressNotValid.selector.revertWith(address(self));
}
}
/// @notice Ensures that the hook address includes at least one hook flag or dynamic fees, or is the 0 address
/// @param self The hook to verify
/// @param fee The fee of the pool the hook is used with
/// @return bool True if the hook address is valid
function isValidHookAddress(IHooks self, uint24 fee) internal pure returns (bool) {
// The hook can only have a flag to return a hook delta on an action if it also has the corresponding action flag
if (!self.hasPermission(BEFORE_SWAP_FLAG) && self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) return false;
if (!self.hasPermission(AFTER_SWAP_FLAG) && self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)) return false;
if (!self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) && self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG))
{
return false;
}
if (
!self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
&& self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
) return false;
// If there is no hook contract set, then fee cannot be dynamic
// If a hook contract is set, it must have at least 1 flag set, or have a dynamic fee
return address(self) == address(0)
? !fee.isDynamicFee()
: (uint160(address(self)) & ALL_HOOK_MASK > 0 || fee.isDynamicFee());
}
/// @notice performs a hook call using the given calldata on the given hook that doesn't return a delta
/// @return result The complete data returned by the hook
function callHook(IHooks self, bytes memory data) internal returns (bytes memory result) {
bool success;
assembly ("memory-safe") {
success := call(gas(), self, 0, add(data, 0x20), mload(data), 0, 0)
}
// Revert with FailedHookCall, containing any error message to bubble up
if (!success) CustomRevert.bubbleUpAndRevertWith(address(self), bytes4(data), HookCallFailed.selector);
// The call was successful, fetch the returned data
assembly ("memory-safe") {
// allocate result byte array from the free memory pointer
result := mload(0x40)
// store new free memory pointer at the end of the array padded to 32 bytes
mstore(0x40, add(result, and(add(returndatasize(), 0x3f), not(0x1f))))
// store length in memory
mstore(result, returndatasize())
// copy return data to result
returndatacopy(add(result, 0x20), 0, returndatasize())
}
// Length must be at least 32 to contain the selector. Check expected selector and returned selector match.
if (result.length < 32 || result.parseSelector() != data.parseSelector()) {
InvalidHookResponse.selector.revertWith();
}
}
/// @notice performs a hook call using the given calldata on the given hook
/// @return int256 The delta returned by the hook
function callHookWithReturnDelta(IHooks self, bytes memory data, bool parseReturn) internal returns (int256) {
bytes memory result = callHook(self, data);
// If this hook wasn't meant to return something, default to 0 delta
if (!parseReturn) return 0;
// A length of 64 bytes is required to return a bytes4, and a 32 byte delta
if (result.length != 64) InvalidHookResponse.selector.revertWith();
return result.parseReturnDelta();
}
/// @notice modifier to prevent calling a hook if they initiated the action
modifier noSelfCall(IHooks self) {
if (msg.sender != address(self)) {
_;
}
}
/// @notice calls beforeInitialize hook if permissioned and validates return value
function beforeInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96) internal noSelfCall(self) {
if (self.hasPermission(BEFORE_INITIALIZE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeInitialize, (msg.sender, key, sqrtPriceX96)));
}
}
/// @notice calls afterInitialize hook if permissioned and validates return value
function afterInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96, int24 tick)
internal
noSelfCall(self)
{
if (self.hasPermission(AFTER_INITIALIZE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.afterInitialize, (msg.sender, key, sqrtPriceX96, tick)));
}
}
/// @notice calls beforeModifyLiquidity hook if permissioned and validates return value
function beforeModifyLiquidity(
IHooks self,
PoolKey memory key,
ModifyLiquidityParams memory params,
bytes calldata hookData
) internal noSelfCall(self) {
if (params.liquidityDelta > 0 && self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeAddLiquidity, (msg.sender, key, params, hookData)));
} else if (params.liquidityDelta <= 0 && self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeRemoveLiquidity, (msg.sender, key, params, hookData)));
}
}
/// @notice calls afterModifyLiquidity hook if permissioned and validates return value
function afterModifyLiquidity(
IHooks self,
PoolKey memory key,
ModifyLiquidityParams memory params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) internal returns (BalanceDelta callerDelta, BalanceDelta hookDelta) {
if (msg.sender == address(self)) return (delta, BalanceDeltaLibrary.ZERO_DELTA);
callerDelta = delta;
if (params.liquidityDelta > 0) {
if (self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)) {
hookDelta = BalanceDelta.wrap(
self.callHookWithReturnDelta(
abi.encodeCall(
IHooks.afterAddLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
),
self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
)
);
callerDelta = callerDelta - hookDelta;
}
} else {
if (self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)) {
hookDelta = BalanceDelta.wrap(
self.callHookWithReturnDelta(
abi.encodeCall(
IHooks.afterRemoveLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
),
self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
)
);
callerDelta = callerDelta - hookDelta;
}
}
}
/// @notice calls beforeSwap hook if permissioned and validates return value
function beforeSwap(IHooks self, PoolKey memory key, SwapParams memory params, bytes calldata hookData)
internal
returns (int256 amountToSwap, BeforeSwapDelta hookReturn, uint24 lpFeeOverride)
{
amountToSwap = params.amountSpecified;
if (msg.sender == address(self)) return (amountToSwap, BeforeSwapDeltaLibrary.ZERO_DELTA, lpFeeOverride);
if (self.hasPermission(BEFORE_SWAP_FLAG)) {
bytes memory result = callHook(self, abi.encodeCall(IHooks.beforeSwap, (msg.sender, key, params, hookData)));
// A length of 96 bytes is required to return a bytes4, a 32 byte delta, and an LP fee
if (result.length != 96) InvalidHookResponse.selector.revertWith();
// dynamic fee pools that want to override the cache fee, return a valid fee with the override flag. If override flag
// is set but an invalid fee is returned, the transaction will revert. Otherwise the current LP fee will be used
if (key.fee.isDynamicFee()) lpFeeOverride = result.parseFee();
// skip this logic for the case where the hook return is 0
if (self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) {
hookReturn = BeforeSwapDelta.wrap(result.parseReturnDelta());
// any return in unspecified is passed to the afterSwap hook for handling
int128 hookDeltaSpecified = hookReturn.getSpecifiedDelta();
// Update the swap amount according to the hook's return, and check that the swap type doesn't change (exact input/output)
if (hookDeltaSpecified != 0) {
bool exactInput = amountToSwap < 0;
amountToSwap += hookDeltaSpecified;
if (exactInput ? amountToSwap > 0 : amountToSwap < 0) {
HookDeltaExceedsSwapAmount.selector.revertWith();
}
}
}
}
}
/// @notice calls afterSwap hook if permissioned and validates return value
function afterSwap(
IHooks self,
PoolKey memory key,
SwapParams memory params,
BalanceDelta swapDelta,
bytes calldata hookData,
BeforeSwapDelta beforeSwapHookReturn
) internal returns (BalanceDelta, BalanceDelta) {
if (msg.sender == address(self)) return (swapDelta, BalanceDeltaLibrary.ZERO_DELTA);
int128 hookDeltaSpecified = beforeSwapHookReturn.getSpecifiedDelta();
int128 hookDeltaUnspecified = beforeSwapHookReturn.getUnspecifiedDelta();
if (self.hasPermission(AFTER_SWAP_FLAG)) {
hookDeltaUnspecified += self.callHookWithReturnDelta(
abi.encodeCall(IHooks.afterSwap, (msg.sender, key, params, swapDelta, hookData)),
self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
).toInt128();
}
BalanceDelta hookDelta;
if (hookDeltaUnspecified != 0 || hookDeltaSpecified != 0) {
hookDelta = (params.amountSpecified < 0 == params.zeroForOne)
? toBalanceDelta(hookDeltaSpecified, hookDeltaUnspecified)
: toBalanceDelta(hookDeltaUnspecified, hookDeltaSpecified);
// the caller has to pay for (or receive) the hook's delta
swapDelta = swapDelta - hookDelta;
}
return (swapDelta, hookDelta);
}
/// @notice calls beforeDonate hook if permissioned and validates return value
function beforeDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
internal
noSelfCall(self)
{
if (self.hasPermission(BEFORE_DONATE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeDonate, (msg.sender, key, amount0, amount1, hookData)));
}
}
/// @notice calls afterDonate hook if permissioned and validates return value
function afterDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
internal
noSelfCall(self)
{
if (self.hasPermission(AFTER_DONATE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.afterDonate, (msg.sender, key, amount0, amount1, hookData)));
}
}
function hasPermission(IHooks self, uint160 flag) internal pure returns (bool) {
return uint160(address(self)) & flag != 0;
}
}
node_modules/@uniswap/v4-periphery/lib/v4-core/src/libraries/LPFeeLibrary.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @notice Library of helper functions for a pools LP fee
library LPFeeLibrary {
using LPFeeLibrary for uint24;
using CustomRevert for bytes4;
/// @notice Thrown when the static or dynamic fee on a pool exceeds 100%.
error LPFeeTooLarge(uint24 fee);
/// @notice An lp fee of exactly 0b1000000... signals a dynamic fee pool. This isn't a valid static fee as it is > MAX_LP_FEE
uint24 public constant DYNAMIC_FEE_FLAG = 0x800000;
/// @notice the second bit of the fee returned by beforeSwap is used to signal if the stored LP fee should be overridden in this swap
// only dynamic-fee pools can return a fee via the beforeSwap hook
uint24 public constant OVERRIDE_FEE_FLAG = 0x400000;
/// @notice mask to remove the override fee flag from a fee returned by the beforeSwaphook
uint24 public constant REMOVE_OVERRIDE_MASK = 0xBFFFFF;
/// @notice the lp fee is represented in hundredths of a bip, so the max is 100%
uint24 public constant MAX_LP_FEE = 1000000;
/// @notice returns true if a pool's LP fee signals that the pool has a dynamic fee
/// @param self The fee to check
/// @return bool True of the fee is dynamic
function isDynamicFee(uint24 self) internal pure returns (bool) {
return self == DYNAMIC_FEE_FLAG;
}
/// @notice returns true if an LP fee is valid, aka not above the maximum permitted fee
/// @param self The fee to check
/// @return bool True of the fee is valid
function isValid(uint24 self) internal pure returns (bool) {
return self <= MAX_LP_FEE;
}
/// @notice validates whether an LP fee is larger than the maximum, and reverts if invalid
/// @param self The fee to validate
function validate(uint24 self) internal pure {
if (!self.isValid()) LPFeeTooLarge.selector.revertWith(self);
}
/// @notice gets and validates the initial LP fee for a pool. Dynamic fee pools have an initial fee of 0.
/// @dev if a dynamic fee pool wants a non-0 initial fee, it should call `updateDynamicLPFee` in the afterInitialize hook
/// @param self The fee to get the initial LP from
/// @return initialFee 0 if the fee is dynamic, otherwise the fee (if valid)
function getInitialLPFee(uint24 self) internal pure returns (uint24) {
// the initial fee for a dynamic fee pool is 0
if (self.isDynamicFee()) return 0;
self.validate();
return self;
}
/// @notice returns true if the fee has the override flag set (2nd highest bit of the uint24)
/// @param self The fee to check
/// @return bool True of the fee has the override flag set
function isOverride(uint24 self) internal pure returns (bool) {
return self & OVERRIDE_FEE_FLAG != 0;
}
/// @notice returns a fee with the override flag removed
/// @param self The fee to remove the override flag from
/// @return fee The fee without the override flag set
function removeOverrideFlag(uint24 self) internal pure returns (uint24) {
return self & REMOVE_OVERRIDE_MASK;
}
/// @notice Removes the override flag and validates the fee (reverts if the fee is too large)
/// @param self The fee to remove the override flag from, and then validate
/// @return fee The fee without the override flag set (if valid)
function removeOverrideFlagAndValidate(uint24 self) internal pure returns (uint24 fee) {
fee = self.removeOverrideFlag();
fee.validate();
}
}
node_modules/@uniswap/v4-periphery/lib/v4-core/src/libraries/ParseBytes.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Parses bytes returned from hooks and the byte selector used to check return selectors from hooks.
/// @dev parseSelector also is used to parse the expected selector
/// For parsing hook returns, note that all hooks return either bytes4 or (bytes4, 32-byte-delta) or (bytes4, 32-byte-delta, uint24).
library ParseBytes {
function parseSelector(bytes memory result) internal pure returns (bytes4 selector) {
// equivalent: (selector,) = abi.decode(result, (bytes4, int256));
assembly ("memory-safe") {
selector := mload(add(result, 0x20))
}
}
function parseFee(bytes memory result) internal pure returns (uint24 lpFee) {
// equivalent: (,, lpFee) = abi.decode(result, (bytes4, int256, uint24));
assembly ("memory-safe") {
lpFee := mload(add(result, 0x60))
}
}
function parseReturnDelta(bytes memory result) internal pure returns (int256 hookReturn) {
// equivalent: (, hookReturnDelta) = abi.decode(result, (bytes4, int256));
assembly ("memory-safe") {
hookReturn := mload(add(result, 0x40))
}
}
}
node_modules/@uniswap/v4-periphery/lib/v4-core/src/libraries/SafeCast.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
using CustomRevert for bytes4;
error SafeCastOverflow();
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint160
function toUint160(uint256 x) internal pure returns (uint160 y) {
y = uint160(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint128
function toUint128(uint256 x) internal pure returns (uint128 y) {
y = uint128(x);
if (x != y) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a int128 to a uint128, revert on overflow or underflow
/// @param x The int128 to be casted
/// @return y The casted integer, now type uint128
function toUint128(int128 x) internal pure returns (uint128 y) {
if (x < 0) SafeCastOverflow.selector.revertWith();
y = uint128(x);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param x The int256 to be downcasted
/// @return y The downcasted integer, now type int128
function toInt128(int256 x) internal pure returns (int128 y) {
y = int128(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param x The uint256 to be casted
/// @return y The casted integer, now type int256
function toInt256(uint256 x) internal pure returns (int256 y) {
y = int256(x);
if (y < 0) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return The downcasted integer, now type int128
function toInt128(uint256 x) internal pure returns (int128) {
if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();
return int128(int256(x));
}
}
node_modules/@uniswap/v4-periphery/lib/v4-core/src/types/BalanceDelta.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCast} from "../libraries/SafeCast.sol";
/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;
using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;
function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
assembly ("memory-safe") {
balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
}
}
function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := add(a0, b0)
res1 := add(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := sub(a0, b0)
res1 := sub(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}
function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}
/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
/// @notice A BalanceDelta of 0
BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);
function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
assembly ("memory-safe") {
_amount0 := sar(128, balanceDelta)
}
}
function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
assembly ("memory-safe") {
_amount1 := signextend(15, balanceDelta)
}
}
}
node_modules/@uniswap/v4-periphery/lib/v4-core/src/types/BeforeSwapDelta.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;
// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
pure
returns (BeforeSwapDelta beforeSwapDelta)
{
assembly ("memory-safe") {
beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
}
}
/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
/// @notice A BeforeSwapDelta of 0
BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);
/// extracts int128 from the upper 128 bits of the BeforeSwapDelta
/// returned by beforeSwap
function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
assembly ("memory-safe") {
deltaSpecified := sar(128, delta)
}
}
/// extracts int128 from the lower 128 bits of the BeforeSwapDelta
/// returned by beforeSwap and afterSwap
function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
assembly ("memory-safe") {
deltaUnspecified := signextend(15, delta)
}
}
}
node_modules/@uniswap/v4-periphery/lib/v4-core/src/types/Currency.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";
type Currency is address;
using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;
function equals(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(other);
}
function greaterThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) > Currency.unwrap(other);
}
function lessThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) < Currency.unwrap(other);
}
function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) >= Currency.unwrap(other);
}
/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
/// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
error NativeTransferFailed();
/// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
error ERC20TransferFailed();
/// @notice A constant to represent the native currency
Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));
function transfer(Currency currency, address to, uint256 amount) internal {
// altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
// modified custom error selectors
bool success;
if (currency.isAddressZero()) {
assembly ("memory-safe") {
// Transfer the ETH and revert if it fails.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
// revert with NativeTransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
}
} else {
assembly ("memory-safe") {
// Get a pointer to some free memory.
let fmp := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
success :=
and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), currency, 0, fmp, 68, 0, 32)
)
// Now clean the memory we used
mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
}
// revert with ERC20TransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(
Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
);
}
}
}
function balanceOfSelf(Currency currency) internal view returns (uint256) {
if (currency.isAddressZero()) {
return address(this).balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
}
}
function balanceOf(Currency currency, address owner) internal view returns (uint256) {
if (currency.isAddressZero()) {
return owner.balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
}
}
function isAddressZero(Currency currency) internal pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
}
function toId(Currency currency) internal pure returns (uint256) {
return uint160(Currency.unwrap(currency));
}
// If the upper 12 bytes are non-zero, they will be zero-ed out
// Therefore, fromId() and toId() are not inverses of each other
function fromId(uint256 id) internal pure returns (Currency) {
return Currency.wrap(address(uint160(id)));
}
}
node_modules/@uniswap/v4-periphery/lib/v4-core/src/types/PoolId.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "./PoolKey.sol";
type PoolId is bytes32;
/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
/// @notice Returns value equal to keccak256(abi.encode(poolKey))
function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
assembly ("memory-safe") {
// 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
poolId := keccak256(poolKey, 0xa0)
}
}
}
node_modules/@uniswap/v4-periphery/lib/v4-core/src/types/PoolKey.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";
using PoolIdLibrary for PoolKey global;
/// @notice Returns the key for identifying a pool
struct PoolKey {
/// @notice The lower currency of the pool, sorted numerically
Currency currency0;
/// @notice The higher currency of the pool, sorted numerically
Currency currency1;
/// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
uint24 fee;
/// @notice Ticks that involve positions must be a multiple of tick spacing
int24 tickSpacing;
/// @notice The hooks of the pool
IHooks hooks;
}
node_modules/@uniswap/v4-periphery/lib/v4-core/src/types/PoolOperation.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
/// @notice Parameter struct for `ModifyLiquidity` pool operations
struct ModifyLiquidityParams {
// the lower and upper tick of the position
int24 tickLower;
int24 tickUpper;
// how to modify the liquidity
int256 liquidityDelta;
// a value to set if you want unique liquidity positions at the same range
bytes32 salt;
}
/// @notice Parameter struct for `Swap` pool operations
struct SwapParams {
/// Whether to swap token0 for token1 or vice versa
bool zeroForOne;
/// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
int256 amountSpecified;
/// The sqrt price at which, if reached, the swap will stop executing
uint160 sqrtPriceLimitX96;
}
node_modules/@uniswap/v4-periphery/src/base/ImmutableState.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IImmutableState} from "../interfaces/IImmutableState.sol";
/// @title Immutable State
/// @notice A collection of immutable state variables, commonly used across multiple contracts
contract ImmutableState is IImmutableState {
/// @inheritdoc IImmutableState
IPoolManager public immutable poolManager;
/// @notice Thrown when the caller is not PoolManager
error NotPoolManager();
/// @notice Only allow calls from the PoolManager contract
modifier onlyPoolManager() {
if (msg.sender != address(poolManager)) revert NotPoolManager();
_;
}
constructor(IPoolManager _poolManager) {
poolManager = _poolManager;
}
}
node_modules/@uniswap/v4-periphery/src/interfaces/IEIP712_v4.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IEIP712_v4
/// @notice Interface for the EIP712 contract
interface IEIP712_v4 {
/// @notice Returns the domain separator for the current chain.
/// @return bytes32 The domain separator
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
node_modules/@uniswap/v4-periphery/src/interfaces/IERC721Permit_v4.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IERC721Permit_v4
/// @notice Interface for the ERC721Permit_v4 contract
interface IERC721Permit_v4 {
error SignatureDeadlineExpired();
error NoSelfPermit();
error Unauthorized();
/// @notice Approve of a specific token ID for spending by spender via signature
/// @param spender The account that is being approved
/// @param tokenId The ID of the token that is being approved for spending
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param nonce a unique value, for an owner, to prevent replay attacks; an unordered nonce where the top 248 bits correspond to a word and the bottom 8 bits calculate the bit position of the word
/// @param signature Concatenated data from a valid secp256k1 signature from the holder, i.e. abi.encodePacked(r, s, v)
/// @dev payable so it can be multicalled with NATIVE related actions
function permit(address spender, uint256 tokenId, uint256 deadline, uint256 nonce, bytes calldata signature)
external
payable;
/// @notice Set an operator with full permission to an owner's tokens via signature
/// @param owner The address that is setting the operator
/// @param operator The address that will be set as an operator for the owner
/// @param approved The permission to set on the operator
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param nonce a unique value, for an owner, to prevent replay attacks; an unordered nonce where the top 248 bits correspond to a word and the bottom 8 bits calculate the bit position of the word
/// @param signature Concatenated data from a valid secp256k1 signature from the holder, i.e. abi.encodePacked(r, s, v)
/// @dev payable so it can be multicalled with NATIVE related actions
function permitForAll(
address owner,
address operator,
bool approved,
uint256 deadline,
uint256 nonce,
bytes calldata signature
) external payable;
}
node_modules/@uniswap/v4-periphery/src/interfaces/IImmutableState.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
/// @title IImmutableState
/// @notice Interface for the ImmutableState contract
interface IImmutableState {
/// @notice The Uniswap v4 PoolManager contract
function poolManager() external view returns (IPoolManager);
}
node_modules/@uniswap/v4-periphery/src/interfaces/IMulticall_v4.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IMulticall_v4
/// @notice Interface for the Multicall_v4 contract
interface IMulticall_v4 {
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
/// @dev The `msg.value` is passed onto all subcalls, even if a previous subcall has consumed the ether.
/// Subcalls can instead use `address(this).value` to see the available ETH, and consume it using {value: x}.
/// @param data The encoded function data for each of the calls to make to this contract
/// @return results The results from each of the calls passed in via data
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}
node_modules/@uniswap/v4-periphery/src/interfaces/INotifier.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {ISubscriber} from "./ISubscriber.sol";
/// @title INotifier
/// @notice Interface for the Notifier contract
interface INotifier {
/// @notice Thrown when unsubscribing without a subscriber
error NotSubscribed();
/// @notice Thrown when a subscriber does not have code
error NoCodeSubscriber();
/// @notice Thrown when a user specifies a gas limit too low to avoid valid unsubscribe notifications
error GasLimitTooLow();
/// @notice Wraps the revert message of the subscriber contract on a reverting subscription
error SubscriptionReverted(address subscriber, bytes reason);
/// @notice Wraps the revert message of the subscriber contract on a reverting modify liquidity notification
error ModifyLiquidityNotificationReverted(address subscriber, bytes reason);
/// @notice Wraps the revert message of the subscriber contract on a reverting burn notification
error BurnNotificationReverted(address subscriber, bytes reason);
/// @notice Thrown when a tokenId already has a subscriber
error AlreadySubscribed(uint256 tokenId, address subscriber);
/// @notice Emitted on a successful call to subscribe
event Subscription(uint256 indexed tokenId, address indexed subscriber);
/// @notice Emitted on a successful call to unsubscribe
event Unsubscription(uint256 indexed tokenId, address indexed subscriber);
/// @notice Returns the subscriber for a respective position
/// @param tokenId the ERC721 tokenId
/// @return subscriber the subscriber contract
function subscriber(uint256 tokenId) external view returns (ISubscriber subscriber);
/// @notice Enables the subscriber to receive notifications for a respective position
/// @param tokenId the ERC721 tokenId
/// @param newSubscriber the address of the subscriber contract
/// @param data caller-provided data that's forwarded to the subscriber contract
/// @dev Calling subscribe when a position is already subscribed will revert
/// @dev payable so it can be multicalled with NATIVE related actions
/// @dev will revert if pool manager is locked
function subscribe(uint256 tokenId, address newSubscriber, bytes calldata data) external payable;
/// @notice Removes the subscriber from receiving notifications for a respective position
/// @param tokenId the ERC721 tokenId
/// @dev Callers must specify a high gas limit (remaining gas should be higher than unsubscriberGasLimit) such that the subscriber can be notified
/// @dev payable so it can be multicalled with NATIVE related actions
/// @dev Must always allow a user to unsubscribe. In the case of a malicious subscriber, a user can always unsubscribe safely, ensuring liquidity is always modifiable.
/// @dev will revert if pool manager is locked
function unsubscribe(uint256 tokenId) external payable;
/// @notice Returns and determines the maximum allowable gas-used for notifying unsubscribe
/// @return uint256 the maximum gas limit when notifying a subscriber's `notifyUnsubscribe` function
function unsubscribeGasLimit() external view returns (uint256);
}
node_modules/@uniswap/v4-periphery/src/interfaces/IPermit2Forwarder.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IAllowanceTransfer} from "permit2/src/interfaces/IAllowanceTransfer.sol";
/// @title IPermit2Forwarder
/// @notice Interface for the Permit2Forwarder contract
interface IPermit2Forwarder {
/// @notice allows forwarding a single permit to permit2
/// @dev this function is payable to allow multicall with NATIVE based actions
/// @param owner the owner of the tokens
/// @param permitSingle the permit data
/// @param signature the signature of the permit; abi.encodePacked(r, s, v)
/// @return err the error returned by a reverting permit call, empty if successful
function permit(address owner, IAllowanceTransfer.PermitSingle calldata permitSingle, bytes calldata signature)
external
payable
returns (bytes memory err);
/// @notice allows forwarding batch permits to permit2
/// @dev this function is payable to allow multicall with NATIVE based actions
/// @param owner the owner of the tokens
/// @param _permitBatch a batch of approvals
/// @param signature the signature of the permit; abi.encodePacked(r, s, v)
/// @return err the error returned by a reverting permit call, empty if successful
function permitBatch(address owner, IAllowanceTransfer.PermitBatch calldata _permitBatch, bytes calldata signature)
external
payable
returns (bytes memory err);
}
node_modules/@uniswap/v4-periphery/src/interfaces/IPoolInitializer_v4.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
/// @title IPoolInitializer_v4
/// @notice Interface for the PoolInitializer_v4 contract
interface IPoolInitializer_v4 {
/// @notice Initialize a Uniswap v4 Pool
/// @dev If the pool is already initialized, this function will not revert and just return type(int24).max
/// @param key The PoolKey of the pool to initialize
/// @param sqrtPriceX96 The initial starting price of the pool, expressed as a sqrtPriceX96
/// @return The current tick of the pool, or type(int24).max if the pool creation failed, or the pool already existed
function initializePool(PoolKey calldata key, uint160 sqrtPriceX96) external payable returns (int24);
}
node_modules/@uniswap/v4-periphery/src/interfaces/IPositionManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PositionInfo} from "../libraries/PositionInfoLibrary.sol";
import {INotifier} from "./INotifier.sol";
import {IImmutableState} from "./IImmutableState.sol";
import {IERC721Permit_v4} from "./IERC721Permit_v4.sol";
import {IEIP712_v4} from "./IEIP712_v4.sol";
import {IMulticall_v4} from "./IMulticall_v4.sol";
import {IPoolInitializer_v4} from "./IPoolInitializer_v4.sol";
import {IUnorderedNonce} from "./IUnorderedNonce.sol";
import {IPermit2Forwarder} from "./IPermit2Forwarder.sol";
/// @title IPositionManager
/// @notice Interface for the PositionManager contract
interface IPositionManager is
INotifier,
IImmutableState,
IERC721Permit_v4,
IEIP712_v4,
IMulticall_v4,
IPoolInitializer_v4,
IUnorderedNonce,
IPermit2Forwarder
{
/// @notice Thrown when the caller is not approved to modify a position
error NotApproved(address caller);
/// @notice Thrown when the block.timestamp exceeds the user-provided deadline
error DeadlinePassed(uint256 deadline);
/// @notice Thrown when calling transfer, subscribe, or unsubscribe when the PoolManager is unlocked.
/// @dev This is to prevent hooks from being able to trigger notifications at the same time the position is being modified.
error PoolManagerMustBeLocked();
/// @notice Unlocks Uniswap v4 PoolManager and batches actions for modifying liquidity
/// @dev This is the standard entrypoint for the PositionManager
/// @param unlockData is an encoding of actions, and parameters for those actions
/// @param deadline is the deadline for the batched actions to be executed
function modifyLiquidities(bytes calldata unlockData, uint256 deadline) external payable;
/// @notice Batches actions for modifying liquidity without unlocking v4 PoolManager
/// @dev This must be called by a contract that has already unlocked the v4 PoolManager
/// @param actions the actions to perform
/// @param params the parameters to provide for the actions
function modifyLiquiditiesWithoutUnlock(bytes calldata actions, bytes[] calldata params) external payable;
/// @notice Used to get the ID that will be used for the next minted liquidity position
/// @return uint256 The next token ID
function nextTokenId() external view returns (uint256);
/// @notice Returns the liquidity of a position
/// @param tokenId the ERC721 tokenId
/// @return liquidity the position's liquidity, as a liquidityAmount
/// @dev this value can be processed as an amount0 and amount1 by using the LiquidityAmounts library
function getPositionLiquidity(uint256 tokenId) external view returns (uint128 liquidity);
/// @notice Returns the pool key and position info of a position
/// @param tokenId the ERC721 tokenId
/// @return poolKey the pool key of the position
/// @return PositionInfo a uint256 packed value holding information about the position including the range (tickLower, tickUpper)
function getPoolAndPositionInfo(uint256 tokenId) external view returns (PoolKey memory, PositionInfo);
/// @notice Returns the position info of a position
/// @param tokenId the ERC721 tokenId
/// @return a uint256 packed value holding information about the position including the range (tickLower, tickUpper)
function positionInfo(uint256 tokenId) external view returns (PositionInfo);
}
node_modules/@uniswap/v4-periphery/src/interfaces/ISubscriber.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {PositionInfo} from "../libraries/PositionInfoLibrary.sol";
/// @title ISubscriber
/// @notice Interface that a Subscriber contract should implement to receive updates from the v4 position manager
interface ISubscriber {
/// @notice Called when a position subscribes to this subscriber contract
/// @param tokenId the token ID of the position
/// @param data additional data passed in by the caller
function notifySubscribe(uint256 tokenId, bytes memory data) external;
/// @notice Called when a position unsubscribes from the subscriber
/// @dev This call's gas is capped at `unsubscribeGasLimit` (set at deployment)
/// @dev Because of EIP-150, solidity may only allocate 63/64 of gasleft()
/// @param tokenId the token ID of the position
function notifyUnsubscribe(uint256 tokenId) external;
/// @notice Called when a position is burned
/// @param tokenId the token ID of the position
/// @param owner the current owner of the tokenId
/// @param info information about the position
/// @param liquidity the amount of liquidity decreased in the position, may be 0
/// @param feesAccrued the fees accrued by the position if liquidity was decreased
function notifyBurn(uint256 tokenId, address owner, PositionInfo info, uint256 liquidity, BalanceDelta feesAccrued)
external;
/// @notice Called when a position modifies its liquidity or collects fees
/// @param tokenId the token ID of the position
/// @param liquidityChange the change in liquidity on the underlying position
/// @param feesAccrued the fees to be collected from the position as a result of the modifyLiquidity call
/// @dev Note that feesAccrued can be artificially inflated by a malicious user
/// Pools with a single liquidity position can inflate feeGrowthGlobal (and consequently feesAccrued) by donating to themselves;
/// atomically donating and collecting fees within the same unlockCallback may further inflate feeGrowthGlobal/feesAccrued
function notifyModifyLiquidity(uint256 tokenId, int256 liquidityChange, BalanceDelta feesAccrued) external;
}
node_modules/@uniswap/v4-periphery/src/interfaces/IUnorderedNonce.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IUnorderedNonce
/// @notice Interface for the UnorderedNonce contract
interface IUnorderedNonce {
error NonceAlreadyUsed();
/// @notice mapping of nonces consumed by each address, where a nonce is a single bit on the 256-bit bitmap
/// @dev word is at most type(uint248).max
function nonces(address owner, uint256 word) external view returns (uint256);
/// @notice Revoke a nonce by spending it, preventing it from being used again
/// @dev Used in cases where a valid nonce has not been broadcasted onchain, and the owner wants to revoke the validity of the nonce
/// @dev payable so it can be multicalled with native-token related actions
function revokeNonce(uint256 nonce) external payable;
}
node_modules/@uniswap/v4-periphery/src/libraries/PositionInfoLibrary.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
/**
* @dev PositionInfo is a packed version of solidity structure.
* Using the packaged version saves gas and memory by not storing the structure fields in memory slots.
*
* Layout:
* 200 bits poolId | 24 bits tickUpper | 24 bits tickLower | 8 bits hasSubscriber
*
* Fields in the direction from the least significant bit:
*
* A flag to know if the tokenId is subscribed to an address
* uint8 hasSubscriber;
*
* The tickUpper of the position
* int24 tickUpper;
*
* The tickLower of the position
* int24 tickLower;
*
* The truncated poolId. Truncates a bytes32 value so the most signifcant (highest) 200 bits are used.
* bytes25 poolId;
*
* Note: If more bits are needed, hasSubscriber can be a single bit.
*
*/
type PositionInfo is uint256;
using PositionInfoLibrary for PositionInfo global;
library PositionInfoLibrary {
PositionInfo internal constant EMPTY_POSITION_INFO = PositionInfo.wrap(0);
uint256 internal constant MASK_UPPER_200_BITS = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000;
uint256 internal constant MASK_8_BITS = 0xFF;
uint24 internal constant MASK_24_BITS = 0xFFFFFF;
uint256 internal constant SET_UNSUBSCRIBE = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00;
uint256 internal constant SET_SUBSCRIBE = 0x01;
uint8 internal constant TICK_LOWER_OFFSET = 8;
uint8 internal constant TICK_UPPER_OFFSET = 32;
/// @dev This poolId is NOT compatible with the poolId used in UniswapV4 core. It is truncated to 25 bytes, and just used to lookup PoolKey in the poolKeys mapping.
function poolId(PositionInfo info) internal pure returns (bytes25 _poolId) {
assembly ("memory-safe") {
_poolId := and(MASK_UPPER_200_BITS, info)
}
}
function tickLower(PositionInfo info) internal pure returns (int24 _tickLower) {
assembly ("memory-safe") {
_tickLower := signextend(2, shr(TICK_LOWER_OFFSET, info))
}
}
function tickUpper(PositionInfo info) internal pure returns (int24 _tickUpper) {
assembly ("memory-safe") {
_tickUpper := signextend(2, shr(TICK_UPPER_OFFSET, info))
}
}
function hasSubscriber(PositionInfo info) internal pure returns (bool _hasSubscriber) {
assembly ("memory-safe") {
_hasSubscriber := and(MASK_8_BITS, info)
}
}
/// @dev this does not actually set any storage
function setSubscribe(PositionInfo info) internal pure returns (PositionInfo _info) {
assembly ("memory-safe") {
_info := or(info, SET_SUBSCRIBE)
}
}
/// @dev this does not actually set any storage
function setUnsubscribe(PositionInfo info) internal pure returns (PositionInfo _info) {
assembly ("memory-safe") {
_info := and(info, SET_UNSUBSCRIBE)
}
}
/// @notice Creates the default PositionInfo struct
/// @dev Called when minting a new position
/// @param _poolKey the pool key of the position
/// @param _tickLower the lower tick of the position
/// @param _tickUpper the upper tick of the position
/// @return info packed position info, with the truncated poolId and the hasSubscriber flag set to false
function initialize(PoolKey memory _poolKey, int24 _tickLower, int24 _tickUpper)
internal
pure
returns (PositionInfo info)
{
bytes25 _poolId = bytes25(PoolId.unwrap(_poolKey.toId()));
assembly {
info :=
or(
or(and(MASK_UPPER_200_BITS, _poolId), shl(TICK_UPPER_OFFSET, and(MASK_24_BITS, _tickUpper))),
shl(TICK_LOWER_OFFSET, and(MASK_24_BITS, _tickLower))
)
}
}
}
node_modules/@uniswap/v4-periphery/src/utils/BaseHook.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {BeforeSwapDelta} from "@uniswap/v4-core/src/types/BeforeSwapDelta.sol";
import {ImmutableState} from "../base/ImmutableState.sol";
import {ModifyLiquidityParams, SwapParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";
/// @title Base Hook
/// @notice abstract contract for hook implementations
abstract contract BaseHook is IHooks, ImmutableState {
error HookNotImplemented();
constructor(IPoolManager _manager) ImmutableState(_manager) {
validateHookAddress(this);
}
/// @notice Returns a struct of permissions to signal which hook functions are to be implemented
/// @dev Used at deployment to validate the address correctly represents the expected permissions
/// @return Permissions struct
function getHookPermissions() public pure virtual returns (Hooks.Permissions memory);
/// @notice Validates the deployed hook address agrees with the expected permissions of the hook
/// @dev this function is virtual so that we can override it during testing,
/// which allows us to deploy an implementation to any address
/// and then etch the bytecode into the correct address
function validateHookAddress(BaseHook _this) internal pure virtual {
Hooks.validateHookPermissions(_this, getHookPermissions());
}
/// @inheritdoc IHooks
function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96)
external
onlyPoolManager
returns (bytes4)
{
return _beforeInitialize(sender, key, sqrtPriceX96);
}
function _beforeInitialize(address, PoolKey calldata, uint160) internal virtual returns (bytes4) {
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
external
onlyPoolManager
returns (bytes4)
{
return _afterInitialize(sender, key, sqrtPriceX96, tick);
}
function _afterInitialize(address, PoolKey calldata, uint160, int24) internal virtual returns (bytes4) {
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function beforeAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external onlyPoolManager returns (bytes4) {
return _beforeAddLiquidity(sender, key, params, hookData);
}
function _beforeAddLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)
internal
virtual
returns (bytes4)
{
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function beforeRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external onlyPoolManager returns (bytes4) {
return _beforeRemoveLiquidity(sender, key, params, hookData);
}
function _beforeRemoveLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)
internal
virtual
returns (bytes4)
{
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function afterAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external onlyPoolManager returns (bytes4, BalanceDelta) {
return _afterAddLiquidity(sender, key, params, delta, feesAccrued, hookData);
}
function _afterAddLiquidity(
address,
PoolKey calldata,
ModifyLiquidityParams calldata,
BalanceDelta,
BalanceDelta,
bytes calldata
) internal virtual returns (bytes4, BalanceDelta) {
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function afterRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external onlyPoolManager returns (bytes4, BalanceDelta) {
return _afterRemoveLiquidity(sender, key, params, delta, feesAccrued, hookData);
}
function _afterRemoveLiquidity(
address,
PoolKey calldata,
ModifyLiquidityParams calldata,
BalanceDelta,
BalanceDelta,
bytes calldata
) internal virtual returns (bytes4, BalanceDelta) {
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
external
onlyPoolManager
returns (bytes4, BeforeSwapDelta, uint24)
{
return _beforeSwap(sender, key, params, hookData);
}
function _beforeSwap(address, PoolKey calldata, SwapParams calldata, bytes calldata)
internal
virtual
returns (bytes4, BeforeSwapDelta, uint24)
{
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function afterSwap(
address sender,
PoolKey calldata key,
SwapParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) external onlyPoolManager returns (bytes4, int128) {
return _afterSwap(sender, key, params, delta, hookData);
}
function _afterSwap(address, PoolKey calldata, SwapParams calldata, BalanceDelta, bytes calldata)
internal
virtual
returns (bytes4, int128)
{
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function beforeDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external onlyPoolManager returns (bytes4) {
return _beforeDonate(sender, key, amount0, amount1, hookData);
}
function _beforeDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)
internal
virtual
returns (bytes4)
{
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function afterDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external onlyPoolManager returns (bytes4) {
return _afterDonate(sender, key, amount0, amount1, hookData);
}
function _afterDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)
internal
virtual
returns (bytes4)
{
revert HookNotImplemented();
}
}
src/platform/hook/HookFeeMath.sol
// SPDX-License-Identifier: MIT
/*
╔═══════════════════════════════════════════════════════════════════════════════════════╗
║ ▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚ ║
║ ▞ ▚ ║
║ ▞ ┌─[ SYS ]──────────────────────────────────────────────────────────[ v4 ]─┐ ▚ ║
║ ▞ │ ◉ ONLINE ◎ UNISWAP v4 ◎ ETHEREUM MAINNET ◎ PERMISSIONLESS LAUNCH │ ▚ ║
║ ▞ └─────────────────────────────────────────────────────────────────────────┘ ▚ ║
║ ▞ ▚ ║
║ ▞ ▄████████▄ ██ ██ ████████ ██ ████████ ██ ██ ███ ██ ▚ ║
║ ▞ ██▀▀▀▀▀▀▀▀ ██ ▄▄ ██ ██▀▀▀▀▀▀ ██ ██▀▀▀▀▀▀ ██ ██ ████▄ ██ ▚ ║
║ ▞ ██ ▄████▄ ██ ████ ██ ██████ ██ ██████ ██ ██ ██ ▀██▄██ ▚ ║
║ ▞ ██ ▀▀▀▀██ ██▀█▀▀█▀██ ██▄▄▄▄▄▄ ██ ▄▄ ██ ▀██▄▄██▀ ██ ▀███ ▚ ║
║ ▞ ▀████████▀ ▀██▀ ▀██▀ ████████ ██ ▀▀ ██ ▀████▀ ██ ▀██ ▚ ║
║ ▞ ▚ ║
║ ▞ ╭─────────────────────────────────────────────────────────────────────────╮ ▚ ║
║ ▞ │ ░▒▓█▓▒░ T O K E N L A U N C H P A D · H O O K P O W E R E D │ ▚ ║
║ ▞ ╰─────────────────────────────────────────────────────────────────────────╯ ▚ ║
║ ▞ ▚ ║
║ ▞ ┌──────────────────────────────────┐ ┌──────────────────────────────────┐ ▚ ║
║ ▞ │ ◈ https://gwei.fun/ │ │ ✕ https://x.com/gweidotfun │ ▚ ║
║ ▞ └──────────────────────────────────┘ └──────────────────────────────────┘ ▚ ║
║ ▞ ▚ ║
║ ▞ ·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──· ▚ ║
║ ▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚ ║
╚═══════════════════════════════════════════════════════════════════════════════════════╝
*/
pragma solidity 0.8.26;
import {FeeTerms} from "../../shared/IGweiFunFeeHook.sol";
/// @title HookFeeMath
/// @notice Pure rate and amount arithmetic for the swap hook. Every division rounds down.
/// @custom:version 1.1
library HookFeeMath {
string public constant GweiCreator = "Blur";
string public constant LaunchEnabld = "false";
string internal constant VERSION = "1.1";
/// @dev 100% expressed in bips.
uint256 internal constant BIPS = 10_000;
/// @dev Most a single swap can ever be charged (10%), whatever the stored terms say.
uint16 internal constant HARD_CAP_BIPS = 1_000;
/// @notice Opening levy at time `nowTs`: full until the window starts, zero once it ends,
/// and a straight line in between.
function decayedAntiSnipeTax(FeeTerms storage terms, uint256 nowTs) internal view returns (uint256 bips) {
bips = terms.openingLevyBips;
if (bips == 0) return 0;
uint256 from = terms.openingLevyStart;
if (nowTs <= from) return bips;
uint256 until = terms.openingLevyEnd;
if (nowTs >= until) return 0;
bips = (bips * (until - nowTs)) / (until - from);
}
/// @notice Rates applying to one swap direction at time `nowTs`.
/// @return allBips Whole charge, never above {HARD_CAP_BIPS}.
/// @return protocolBips Protocol part of `allBips`, itself bounded by it.
function feeRates(FeeTerms storage terms, bool isBuy, uint256 nowTs)
internal
view
returns (uint256 allBips, uint256 protocolBips)
{
protocolBips = terms.protocolFeeBips;
uint256 directional = isBuy ? terms.buyLevyBips : terms.sellLevyBips;
allBips = protocolBips + directional + decayedAntiSnipeTax(terms, nowTs);
// Second line of defence behind the check made when terms are stored.
if (allBips > HARD_CAP_BIPS) {
allBips = HARD_CAP_BIPS;
if (protocolBips > HARD_CAP_BIPS) protocolBips = HARD_CAP_BIPS;
}
}
/// @notice Charge on `amount` at `allBips`.
function feeAmount(uint256 amount, uint256 allBips) internal pure returns (uint256) {
return (amount * allBips) / BIPS;
}
/// @notice Divides a charge between the payee and the buyback side.
/// @dev The protocol slice is cut out of the charge first, then the buyback takes the part of
/// that slice the creator is not entitled to. The payee keeps the rest, which includes
/// the whole creator levy and all rounding dust. `allBips` must be non-zero.
function splitFee(uint256 charge, uint256 allBips, uint256 protocolBips, uint256 creatorCutBips)
internal
pure
returns (uint256 toPayee, uint256 toBuyback)
{
uint256 protocolSlice = (charge * protocolBips) / allBips;
toBuyback = (protocolSlice * (BIPS - creatorCutBips)) / BIPS;
toPayee = charge - toBuyback;
}
/// @notice Highest charge the given terms could ever produce: protocol fee, the larger of the
/// two directional levies, and the opening levy at full strength.
function worstCaseBips(FeeTerms calldata terms) internal pure returns (uint256) {
uint256 directional = terms.buyLevyBips > terms.sellLevyBips ? terms.buyLevyBips : terms.sellLevyBips;
return uint256(terms.protocolFeeBips) + directional + uint256(terms.openingLevyBips);
}
}
src/platform/hook/HookFeeVault.sol
// SPDX-License-Identifier: MIT
/*
╔═══════════════════════════════════════════════════════════════════════════════════════╗
║ ▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚ ║
║ ▞ ▚ ║
║ ▞ ┌─[ SYS ]──────────────────────────────────────────────────────────[ v4 ]─┐ ▚ ║
║ ▞ │ ◉ ONLINE ◎ UNISWAP v4 ◎ ETHEREUM MAINNET ◎ PERMISSIONLESS LAUNCH │ ▚ ║
║ ▞ └─────────────────────────────────────────────────────────────────────────┘ ▚ ║
║ ▞ ▚ ║
║ ▞ ▄████████▄ ██ ██ ████████ ██ ████████ ██ ██ ███ ██ ▚ ║
║ ▞ ██▀▀▀▀▀▀▀▀ ██ ▄▄ ██ ██▀▀▀▀▀▀ ██ ██▀▀▀▀▀▀ ██ ██ ████▄ ██ ▚ ║
║ ▞ ██ ▄████▄ ██ ████ ██ ██████ ██ ██████ ██ ██ ██ ▀██▄██ ▚ ║
║ ▞ ██ ▀▀▀▀██ ██▀█▀▀█▀██ ██▄▄▄▄▄▄ ██ ▄▄ ██ ▀██▄▄██▀ ██ ▀███ ▚ ║
║ ▞ ▀████████▀ ▀██▀ ▀██▀ ████████ ██ ▀▀ ██ ▀████▀ ██ ▀██ ▚ ║
║ ▞ ▚ ║
║ ▞ ╭─────────────────────────────────────────────────────────────────────────╮ ▚ ║
║ ▞ │ ░▒▓█▓▒░ T O K E N L A U N C H P A D · H O O K P O W E R E D │ ▚ ║
║ ▞ ╰─────────────────────────────────────────────────────────────────────────╯ ▚ ║
║ ▞ ▚ ║
║ ▞ ┌──────────────────────────────────┐ ┌──────────────────────────────────┐ ▚ ║
║ ▞ │ ◈ https://gwei.fun/ │ │ ✕ https://x.com/gweidotfun │ ▚ ║
║ ▞ └──────────────────────────────────┘ └──────────────────────────────────┘ ▚ ║
║ ▞ ▚ ║
║ ▞ ·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──· ▚ ║
║ ▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚ ║
╚═══════════════════════════════════════════════════════════════════════════════════════╝
*/
pragma solidity 0.8.26;
import {IUnlockCallback} from "@uniswap/v4-core/src/interfaces/callback/IUnlockCallback.sol";
import {Currency, CurrencyLibrary} from "@uniswap/v4-core/src/types/Currency.sol";
import {ImmutableState} from "@uniswap/v4-periphery/src/base/ImmutableState.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {PoolFeeTerms} from "./PoolFeeTerms.sol";
/// @title HookFeeVault
/// @notice Bookkeeping for charged fees. Balances are backed one-to-one by ERC-6909 claims this
/// contract holds on the PoolManager; paying out burns claims and takes the underlying
/// inside an unlock. Swaps therefore never move a token, and a misbehaving currency can
/// only break its own redemption.
/// @custom:version 1.1
abstract contract HookFeeVault is ImmutableState, PoolFeeTerms, IUnlockCallback, ReentrancyGuard {
using CurrencyLibrary for Currency;
error NothingOwed();
error ArrayLengthsDiffer();
/// @notice payee => currency => creator-side balance. Keyed by payee, not pool, so one call
/// collects across all of a creator's markets.
mapping(address => mapping(Currency => uint256)) public creatorFeesOwed;
/// @notice currency => balance waiting to be forwarded to the buyback engine.
mapping(Currency => uint256) public buybackFeesOwed;
/// @notice Pay the caller's creator-side balances in `currencies` out to `to`.
/// @dev Balances belong to msg.sender, so a contract payee must call this itself. Empty
/// currencies are skipped; the call only reverts when every one of them is empty.
/// @return paid Amount per currency, aligned with `currencies`.
function claimCreatorFees(Currency[] calldata currencies, address to)
external
nonReentrant
returns (uint256[] memory paid)
{
if (to == address(0)) revert NullAddress();
uint256 n = currencies.length;
paid = new uint256[](n);
bool any;
mapping(Currency => uint256) storage mine = creatorFeesOwed[msg.sender];
for (uint256 i = 0; i < n; ++i) {
Currency c = currencies[i];
uint256 due = mine[c];
if (due != 0) {
mine[c] = 0;
paid[i] = due;
any = true;
emit CreatorPayout(to, c, due);
}
}
_redeemClaims(any, currencies, paid, to);
}
/// @notice Send the buyback-side balances in `currencies` to the controller's buyback engine.
/// Anyone may call: the destination is fixed.
/// @return sent Amount per currency, aligned with `currencies`.
function sweepBuybackFees(Currency[] calldata currencies)
external
nonReentrant
returns (uint256[] memory sent)
{
address engine = launchpad.buyback();
if (engine == address(0)) revert NullAddress();
uint256 n = currencies.length;
sent = new uint256[](n);
bool any;
for (uint256 i = 0; i < n; ++i) {
Currency c = currencies[i];
uint256 due = buybackFeesOwed[c];
if (due != 0) {
buybackFeesOwed[c] = 0;
sent[i] = due;
any = true;
emit BuybackForwarded(c, due);
}
}
_redeemClaims(any, currencies, sent, engine);
}
/// @inheritdoc IUnlockCallback
/// @dev Continuation of {_redeemClaims}; balances were already cleared by its caller. For each
/// non-zero entry: burn the claim, then take the asset to the destination.
function unlockCallback(bytes calldata data) external override onlyPoolManager returns (bytes memory) {
(Currency[] memory currencies, uint256[] memory amounts, address to) =
abi.decode(data, (Currency[], uint256[], address));
uint256 n = currencies.length;
if (n != amounts.length) revert ArrayLengthsDiffer();
for (uint256 i = 0; i < n; ++i) {
uint256 value = amounts[i];
if (value != 0) {
Currency c = currencies[i];
poolManager.burn(address(this), c.toId(), value);
poolManager.take(c, to, value);
}
}
return "";
}
/// @dev Books a fresh charge, then mints the matching claim to this contract.
function _accrue(address payee, Currency currency, uint256 toPayee, uint256 toBuyback) internal {
creatorFeesOwed[payee][currency] += toPayee;
buybackFeesOwed[currency] += toBuyback;
poolManager.mint(address(this), currency.toId(), toPayee + toBuyback);
}
function _redeemClaims(bool any, Currency[] calldata currencies, uint256[] memory amounts, address to) private {
if (!any) revert NothingOwed();
poolManager.unlock(abi.encode(currencies, amounts, to));
}
}
src/platform/hook/PoolFeeTerms.sol
// SPDX-License-Identifier: MIT
/*
╔═══════════════════════════════════════════════════════════════════════════════════════╗
║ ▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚ ║
║ ▞ ▚ ║
║ ▞ ┌─[ SYS ]──────────────────────────────────────────────────────────[ v4 ]─┐ ▚ ║
║ ▞ │ ◉ ONLINE ◎ UNISWAP v4 ◎ ETHEREUM MAINNET ◎ PERMISSIONLESS LAUNCH │ ▚ ║
║ ▞ └─────────────────────────────────────────────────────────────────────────┘ ▚ ║
║ ▞ ▚ ║
║ ▞ ▄████████▄ ██ ██ ████████ ██ ████████ ██ ██ ███ ██ ▚ ║
║ ▞ ██▀▀▀▀▀▀▀▀ ██ ▄▄ ██ ██▀▀▀▀▀▀ ██ ██▀▀▀▀▀▀ ██ ██ ████▄ ██ ▚ ║
║ ▞ ██ ▄████▄ ██ ████ ██ ██████ ██ ██████ ██ ██ ██ ▀██▄██ ▚ ║
║ ▞ ██ ▀▀▀▀██ ██▀█▀▀█▀██ ██▄▄▄▄▄▄ ██ ▄▄ ██ ▀██▄▄██▀ ██ ▀███ ▚ ║
║ ▞ ▀████████▀ ▀██▀ ▀██▀ ████████ ██ ▀▀ ██ ▀████▀ ██ ▀██ ▚ ║
║ ▞ ▚ ║
║ ▞ ╭─────────────────────────────────────────────────────────────────────────╮ ▚ ║
║ ▞ │ ░▒▓█▓▒░ T O K E N L A U N C H P A D · H O O K P O W E R E D │ ▚ ║
║ ▞ ╰─────────────────────────────────────────────────────────────────────────╯ ▚ ║
║ ▞ ▚ ║
║ ▞ ┌──────────────────────────────────┐ ┌──────────────────────────────────┐ ▚ ║
║ ▞ │ ◈ https://gwei.fun/ │ │ ✕ https://x.com/gweidotfun │ ▚ ║
║ ▞ └──────────────────────────────────┘ └──────────────────────────────────┘ ▚ ║
║ ▞ ▚ ║
║ ▞ ·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──· ▚ ║
║ ▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚ ║
╚═══════════════════════════════════════════════════════════════════════════════════════╝
*/
pragma solidity 0.8.26;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "@uniswap/v4-core/src/types/PoolId.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {Ownable2Step, Ownable} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {IGweiFunLaunchpad} from "../../shared/IGweiFunLaunchpad.sol";
import {IGweiFunFeeHook, FeeTerms} from "../../shared/IGweiFunFeeHook.sol";
import {HookFeeMath} from "./HookFeeMath.sol";
import {GweiCreatorTag} from "../../shared/GweiCreatorTag.sol";
/// @title PoolFeeTerms
/// @notice Holds the write-once charging terms of each pool, the two address lists the owner
/// curates (term writers and fee-exempt swappers) and the read-only fee quotes.
/// @custom:version 1.1
abstract contract PoolFeeTerms is GweiCreatorTag, IGweiFunFeeHook, Ownable2Step {
using PoolIdLibrary for PoolKey;
error Forbidden();
error TermsExist();
error UnknownPool();
error LevyAboveLimit();
error NullAddress();
error BadDecayWindow();
event ExemptionChanged(address indexed account, bool exempt);
event WriterChanged(address indexed account, bool allowed);
event PayeeChanged(PoolId indexed poolId, address indexed oldRecipient, address indexed newRecipient);
event LevyReduced(PoolId indexed poolId, uint16 buyTaxBps, uint16 sellTaxBps);
/// @notice Ceiling on protocol fee plus creator levy for one swap. Checked when terms are
/// stored and applied again as a clamp on every swap.
uint16 public constant MAX_TOTAL_FEE_BIPS = HookFeeMath.HARD_CAP_BIPS;
/// @notice Source of fee policy and factory approvals.
IGweiFunLaunchpad public immutable launchpad;
/// @notice Swappers that are never charged (the buyback engine, so it pays itself nothing).
mapping(address => bool) public isFeeExempt;
/// @notice Extra accounts allowed to store terms (the pool initializer), besides allowed
/// factories and the owner.
mapping(address => bool) public isTermsWriter;
/// @notice The created token (non pair-asset side) of each pool with terms.
mapping(PoolId => address) public launchedTokenOf;
mapping(PoolId => FeeTerms) internal _terms;
constructor(IGweiFunLaunchpad launchpad_, address owner_) Ownable(owner_) {
if (address(launchpad_) == address(0) || owner_ == address(0)) revert NullAddress();
launchpad = launchpad_;
}
// ------------------------------------------------------------------ owner
/// @notice Switch the fee exemption of `account` on or off.
function setFeeExempt(address account, bool status) external onlyOwner {
isFeeExempt[account] = status;
emit ExemptionChanged(account, status);
}
/// @notice Grant or withdraw the right to store terms.
function setTermsWriter(address account, bool status) external onlyOwner {
_requireAddress(account);
isTermsWriter[account] = status;
emit WriterChanged(account, status);
}
// ------------------------------------------------------------------ terms
/// @inheritdoc IGweiFunFeeHook
/// @dev Open to writers, allowed factories and the owner (the owner path serves the platform
/// token's own pool, which no factory creates). Terms are written exactly once.
function registerPoolTerms(PoolKey calldata key, FeeTerms calldata terms) external {
if (!_canWriteTerms(msg.sender)) revert Forbidden();
PoolId poolId = key.toId();
if (_terms[poolId].active) revert TermsExist();
_requireAddress(terms.payee);
_validateTerms(terms);
FeeTerms storage slot = _terms[poolId];
slot.active = true;
slot.tokenIsZero = terms.tokenIsZero;
slot.creator = terms.creator;
slot.payee = terms.payee;
slot.protocolFeeBips = terms.protocolFeeBips;
slot.creatorCutBips = terms.creatorCutBips;
slot.buyLevyBips = terms.buyLevyBips;
slot.sellLevyBips = terms.sellLevyBips;
slot.openingLevyBips = terms.openingLevyBips;
slot.openingLevyStart = terms.openingLevyStart;
slot.openingLevyEnd = terms.openingLevyEnd;
address token = Currency.unwrap(terms.tokenIsZero ? key.currency0 : key.currency1);
launchedTokenOf[poolId] = token;
emit TermsStored(poolId, token, terms.creator);
}
/// @notice Point a pool's future creator-side fees at `nextPayee`. Creator or current payee
/// only. Balances already accrued stay with the previous payee.
function setFeeRecipient(PoolKey calldata key, address nextPayee) external {
_requireAddress(nextPayee);
(PoolId poolId, FeeTerms storage slot) = _loadTerms(key);
address previous = slot.payee;
if (msg.sender != previous && msg.sender != slot.creator) revert Forbidden();
slot.payee = nextPayee;
emit PayeeChanged(poolId, previous, nextPayee);
}
/// @notice Creator-only, downward-only change of the buy and sell levies.
function lowerCreatorTax(PoolKey calldata key, uint16 buyBips, uint16 sellBips) external {
(PoolId poolId, FeeTerms storage slot) = _loadTerms(key);
if (msg.sender != slot.creator) revert Forbidden();
if (buyBips > slot.buyLevyBips || sellBips > slot.sellLevyBips) revert LevyAboveLimit();
slot.buyLevyBips = buyBips;
slot.sellLevyBips = sellBips;
emit LevyReduced(poolId, buyBips, sellBips);
}
// ------------------------------------------------------------------ views
/// @inheritdoc IGweiFunFeeHook
function poolTerms(PoolId poolId) external view returns (FeeTerms memory) {
return _terms[poolId];
}
/// @inheritdoc IGweiFunFeeHook
function currentFeeBips(PoolId poolId, bool isBuy) external view returns (uint16) {
return uint16(_currentRate(poolId, isBuy));
}
/// @notice Fee, in units of the charged currency, a swap specifying `amount` would pay now.
/// Zero for pools without terms.
function previewFee(PoolId poolId, bool isBuy, uint256 amount) external view returns (uint256) {
return HookFeeMath.feeAmount(amount, _currentRate(poolId, isBuy));
}
// ------------------------------------------------------------------ internals
function _currentRate(PoolId poolId, bool isBuy) private view returns (uint256 allBips) {
FeeTerms storage slot = _terms[poolId];
if (slot.active) (allBips,) = HookFeeMath.feeRates(slot, isBuy, block.timestamp);
}
function _canWriteTerms(address who) private view returns (bool) {
return isTermsWriter[who] || launchpad.isApprovedFactory(who) || who == owner();
}
/// @dev Bounds checks on incoming terms, worst case first against the fixed cap and then
/// against the controller's current ceiling.
function _validateTerms(FeeTerms calldata terms) private view {
if (terms.creatorCutBips > HookFeeMath.BIPS) revert LevyAboveLimit();
uint256 peak = HookFeeMath.worstCaseBips(terms);
if (peak > MAX_TOTAL_FEE_BIPS) revert LevyAboveLimit();
if (peak > launchpad.maxSwapFeeBips()) revert LevyAboveLimit();
if (terms.openingLevyBips != 0 && terms.openingLevyEnd <= terms.openingLevyStart) revert BadDecayWindow();
}
function _loadTerms(PoolKey calldata key) private view returns (PoolId poolId, FeeTerms storage slot) {
poolId = key.toId();
slot = _terms[poolId];
if (!slot.active) revert UnknownPool();
}
function _requireAddress(address a) private pure {
if (a == address(0)) revert NullAddress();
}
}
src/shared/GweiCreatorTag.sol
// SPDX-License-Identifier: MIT
/*
╔═══════════════════════════════════════════════════════════════════════════════════════╗
║ ▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚ ║
║ ▞ ▚ ║
║ ▞ ┌─[ SYS ]──────────────────────────────────────────────────────────[ v4 ]─┐ ▚ ║
║ ▞ │ ◉ ONLINE ◎ UNISWAP v4 ◎ ETHEREUM MAINNET ◎ PERMISSIONLESS LAUNCH │ ▚ ║
║ ▞ └─────────────────────────────────────────────────────────────────────────┘ ▚ ║
║ ▞ ▚ ║
║ ▞ ▄████████▄ ██ ██ ████████ ██ ████████ ██ ██ ███ ██ ▚ ║
║ ▞ ██▀▀▀▀▀▀▀▀ ██ ▄▄ ██ ██▀▀▀▀▀▀ ██ ██▀▀▀▀▀▀ ██ ██ ████▄ ██ ▚ ║
║ ▞ ██ ▄████▄ ██ ████ ██ ██████ ██ ██████ ██ ██ ██ ▀██▄██ ▚ ║
║ ▞ ██ ▀▀▀▀██ ██▀█▀▀█▀██ ██▄▄▄▄▄▄ ██ ▄▄ ██ ▀██▄▄██▀ ██ ▀███ ▚ ║
║ ▞ ▀████████▀ ▀██▀ ▀██▀ ████████ ██ ▀▀ ██ ▀████▀ ██ ▀██ ▚ ║
║ ▞ ▚ ║
║ ▞ ╭─────────────────────────────────────────────────────────────────────────╮ ▚ ║
║ ▞ │ ░▒▓█▓▒░ T O K E N L A U N C H P A D · H O O K P O W E R E D │ ▚ ║
║ ▞ ╰─────────────────────────────────────────────────────────────────────────╯ ▚ ║
║ ▞ ▚ ║
║ ▞ ┌──────────────────────────────────┐ ┌──────────────────────────────────┐ ▚ ║
║ ▞ │ ◈ https://gwei.fun/ │ │ ✕ https://x.com/gweidotfun │ ▚ ║
║ ▞ └──────────────────────────────────┘ └──────────────────────────────────┘ ▚ ║
║ ▞ ▚ ║
║ ▞ ·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──· ▚ ║
║ ▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚ ║
╚═══════════════════════════════════════════════════════════════════════════════════════╝
*/
pragma solidity 0.8.26;
/// @notice Mixin that stamps every contract in the system with its creator, readable as plain
/// text from `GweiCreator()` on any block explorer.
abstract contract GweiCreatorTag {
string public constant GweiCreator = "Blur";
string public constant LaunchEnabld = "false";
}
src/shared/GweiFunVersion.sol
// SPDX-License-Identifier: MIT
/*
╔═══════════════════════════════════════════════════════════════════════════════════════╗
║ ▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚ ║
║ ▞ ▚ ║
║ ▞ ┌─[ SYS ]──────────────────────────────────────────────────────────[ v4 ]─┐ ▚ ║
║ ▞ │ ◉ ONLINE ◎ UNISWAP v4 ◎ ETHEREUM MAINNET ◎ PERMISSIONLESS LAUNCH │ ▚ ║
║ ▞ └─────────────────────────────────────────────────────────────────────────┘ ▚ ║
║ ▞ ▚ ║
║ ▞ ▄████████▄ ██ ██ ████████ ██ ████████ ██ ██ ███ ██ ▚ ║
║ ▞ ██▀▀▀▀▀▀▀▀ ██ ▄▄ ██ ██▀▀▀▀▀▀ ██ ██▀▀▀▀▀▀ ██ ██ ████▄ ██ ▚ ║
║ ▞ ██ ▄████▄ ██ ████ ██ ██████ ██ ██████ ██ ██ ██ ▀██▄██ ▚ ║
║ ▞ ██ ▀▀▀▀██ ██▀█▀▀█▀██ ██▄▄▄▄▄▄ ██ ▄▄ ██ ▀██▄▄██▀ ██ ▀███ ▚ ║
║ ▞ ▀████████▀ ▀██▀ ▀██▀ ████████ ██ ▀▀ ██ ▀████▀ ██ ▀██ ▚ ║
║ ▞ ▚ ║
║ ▞ ╭─────────────────────────────────────────────────────────────────────────╮ ▚ ║
║ ▞ │ ░▒▓█▓▒░ T O K E N L A U N C H P A D · H O O K P O W E R E D │ ▚ ║
║ ▞ ╰─────────────────────────────────────────────────────────────────────────╯ ▚ ║
║ ▞ ▚ ║
║ ▞ ┌──────────────────────────────────┐ ┌──────────────────────────────────┐ ▚ ║
║ ▞ │ ◈ https://gwei.fun/ │ │ ✕ https://x.com/gweidotfun │ ▚ ║
║ ▞ └──────────────────────────────────┘ └──────────────────────────────────┘ ▚ ║
║ ▞ ▚ ║
║ ▞ ·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──· ▚ ║
║ ▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚ ║
╚═══════════════════════════════════════════════════════════════════════════════════════╝
*/
pragma solidity 0.8.26;
import {GweiCreatorTag} from "./GweiCreatorTag.sol";
/// @notice Mixin that stamps a deployed contract with the version of the whole system, readable
/// as plain text from `VERSION()` on any block explorer.
/// @custom:version 1.1
abstract contract GweiFunVersion is GweiCreatorTag {
string public constant VERSION = "1.1";
}
src/shared/IGweiFunFeeHook.sol
// SPDX-License-Identifier: MIT
/*
╔═══════════════════════════════════════════════════════════════════════════════════════╗
║ ▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚ ║
║ ▞ ▚ ║
║ ▞ ┌─[ SYS ]──────────────────────────────────────────────────────────[ v4 ]─┐ ▚ ║
║ ▞ │ ◉ ONLINE ◎ UNISWAP v4 ◎ ETHEREUM MAINNET ◎ PERMISSIONLESS LAUNCH │ ▚ ║
║ ▞ └─────────────────────────────────────────────────────────────────────────┘ ▚ ║
║ ▞ ▚ ║
║ ▞ ▄████████▄ ██ ██ ████████ ██ ████████ ██ ██ ███ ██ ▚ ║
║ ▞ ██▀▀▀▀▀▀▀▀ ██ ▄▄ ██ ██▀▀▀▀▀▀ ██ ██▀▀▀▀▀▀ ██ ██ ████▄ ██ ▚ ║
║ ▞ ██ ▄████▄ ██ ████ ██ ██████ ██ ██████ ██ ██ ██ ▀██▄██ ▚ ║
║ ▞ ██ ▀▀▀▀██ ██▀█▀▀█▀██ ██▄▄▄▄▄▄ ██ ▄▄ ██ ▀██▄▄██▀ ██ ▀███ ▚ ║
║ ▞ ▀████████▀ ▀██▀ ▀██▀ ████████ ██ ▀▀ ██ ▀████▀ ██ ▀██ ▚ ║
║ ▞ ▚ ║
║ ▞ ╭─────────────────────────────────────────────────────────────────────────╮ ▚ ║
║ ▞ │ ░▒▓█▓▒░ T O K E N L A U N C H P A D · H O O K P O W E R E D │ ▚ ║
║ ▞ ╰─────────────────────────────────────────────────────────────────────────╯ ▚ ║
║ ▞ ▚ ║
║ ▞ ┌──────────────────────────────────┐ ┌──────────────────────────────────┐ ▚ ║
║ ▞ │ ◈ https://gwei.fun/ │ │ ✕ https://x.com/gweidotfun │ ▚ ║
║ ▞ └──────────────────────────────────┘ └──────────────────────────────────┘ ▚ ║
║ ▞ ▚ ║
║ ▞ ·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──· ▚ ║
║ ▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚ ║
╚═══════════════════════════════════════════════════════════════════════════════════════╝
*/
pragma solidity 0.8.26;
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
/// @notice Per-pool charging terms held by the hook.
/// @dev Stored once and never refreshed from the GweiFunLaunchpad: the protocol fee and its split are
/// frozen when the market opens, so later policy changes cannot re-price a live pool.
struct FeeTerms {
bool active; // written by the hook; false => unknown pool, initialise is refused
bool tokenIsZero; // created token is currency0 => tells buys from sells
address creator; // sole address that may reduce the levy
address payee; // receives the creator cut; movable by creator or payee
uint16 protocolFeeBips; // frozen copy of GweiFunLaunchpad.platformFeeBips
uint16 creatorCutBips; // frozen copy of GweiFunLaunchpad.creatorShareBips
uint16 buyLevyBips; // creator levy, pair asset -> token
uint16 sellLevyBips; // creator levy, token -> pair asset
uint16 openingLevyBips; // extra anti-sniper levy, fades linearly to zero
uint64 openingLevyStart;
uint64 openingLevyEnd;
}
/// @notice External face of the single hook shared by every pool the system opens.
/// @custom:version 1.1
interface IGweiFunFeeHook {
/// @dev Fired when terms are written, which is always before pool initialisation.
event TermsStored(PoolId indexed poolId, address indexed token, address indexed creator);
/// @dev A swap was charged; amounts are the two slices of the fee.
event LevyTaken(
PoolId indexed poolId, Currency indexed currency, uint256 creatorAmount, uint256 buybackAmount, bool isBuy
);
event CreatorPayout(address indexed recipient, Currency indexed currency, uint256 amount);
event BuybackForwarded(Currency indexed currency, uint256 amount);
/// @dev Must be called before the pool is initialised.
function registerPoolTerms(PoolKey calldata key, FeeTerms calldata terms) external;
function poolTerms(PoolId poolId) external view returns (FeeTerms memory);
/// @dev Unredeemed creator-side balance of `payee` in `currency`.
function creatorFeesOwed(address payee, Currency currency) external view returns (uint256);
/// @dev Unforwarded buyback-side balance in `currency`.
function buybackFeesOwed(Currency currency) external view returns (uint256);
/// @dev Fee in bips a swap would pay at this instant, opening levy included.
function currentFeeBips(PoolId poolId, bool isBuy) external view returns (uint16);
}
src/shared/IGweiFunLaunchpad.sol
// SPDX-License-Identifier: MIT
/*
╔═══════════════════════════════════════════════════════════════════════════════════════╗
║ ▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚ ║
║ ▞ ▚ ║
║ ▞ ┌─[ SYS ]──────────────────────────────────────────────────────────[ v4 ]─┐ ▚ ║
║ ▞ │ ◉ ONLINE ◎ UNISWAP v4 ◎ ETHEREUM MAINNET ◎ PERMISSIONLESS LAUNCH │ ▚ ║
║ ▞ └─────────────────────────────────────────────────────────────────────────┘ ▚ ║
║ ▞ ▚ ║
║ ▞ ▄████████▄ ██ ██ ████████ ██ ████████ ██ ██ ███ ██ ▚ ║
║ ▞ ██▀▀▀▀▀▀▀▀ ██ ▄▄ ██ ██▀▀▀▀▀▀ ██ ██▀▀▀▀▀▀ ██ ██ ████▄ ██ ▚ ║
║ ▞ ██ ▄████▄ ██ ████ ██ ██████ ██ ██████ ██ ██ ██ ▀██▄██ ▚ ║
║ ▞ ██ ▀▀▀▀██ ██▀█▀▀█▀██ ██▄▄▄▄▄▄ ██ ▄▄ ██ ▀██▄▄██▀ ██ ▀███ ▚ ║
║ ▞ ▀████████▀ ▀██▀ ▀██▀ ████████ ██ ▀▀ ██ ▀████▀ ██ ▀██ ▚ ║
║ ▞ ▚ ║
║ ▞ ╭─────────────────────────────────────────────────────────────────────────╮ ▚ ║
║ ▞ │ ░▒▓█▓▒░ T O K E N L A U N C H P A D · H O O K P O W E R E D │ ▚ ║
║ ▞ ╰─────────────────────────────────────────────────────────────────────────╯ ▚ ║
║ ▞ ▚ ║
║ ▞ ┌──────────────────────────────────┐ ┌──────────────────────────────────┐ ▚ ║
║ ▞ │ ◈ https://gwei.fun/ │ │ ✕ https://x.com/gweidotfun │ ▚ ║
║ ▞ └──────────────────────────────────┘ └──────────────────────────────────┘ ▚ ║
║ ▞ ▚ ║
║ ▞ ·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──·──· ▚ ║
║ ▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚▚ ║
╚═══════════════════════════════════════════════════════════════════════════════════════╝
*/
pragma solidity 0.8.26;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IPositionManager} from "@uniswap/v4-periphery/src/interfaces/IPositionManager.sol";
/// @notice Category of an asset that new markets can be priced in. A factory venue serves one
/// category, or every category for the unrestricted venues.
enum AssetClass {
NONE, // never configured
NATIVE, // ETH, i.e. address(0) in v4
STABLE, // dollar stablecoins
STOCK, // tokenized equities
PLATFORM, // the platform's own token
OTHER // anything else the owner has approved
}
/// @notice Catalog entry for one pair asset.
struct PairAsset {
bool active; // switched off => no new markets, entry is kept
AssetClass class_;
uint8 decimals; // cached for UIs
int24 tickSpacing; // used when the creator passes none
uint256 capFloor; // min opening cap, raw pair-asset units, inclusive
uint256 capCeiling; // max opening cap, inclusive; zero means no ceiling
}
/// @notice Permanent record of one created token and its market.
struct Creation {
address token;
address creator; // caller of the factory, also the token owner
address factory;
address pairAsset; // address(0) for ETH
uint64 createdAt;
uint256 positionId; // v4 position NFT, held forever by `token`
PoolKey key; // enough to rebuild the market from this record alone
}
/// @notice What the other parts of the system need from the GweiFunLaunchpad.
/// @custom:version 1.1
interface IGweiFunLaunchpad {
// --- addresses ---
function poolManager() external view returns (IPoolManager);
function positionManager() external view returns (IPositionManager);
function permit2() external view returns (address);
function feeHook() external view returns (address);
function gweiToken() external view returns (address);
function buyback() external view returns (address);
function treasury() external view returns (address);
// --- fee schedule (all in bips, 100 = 1%) ---
function platformFeeBips() external view returns (uint16);
/// @dev Portion of the protocol fee owed to the token creator, in bips of that fee.
function creatorShareBips() external view returns (uint16);
/// @dev Portion of the protocol fee owed to the buyback engine, in bips of that fee.
function buybackShareBips() external view returns (uint16);
/// @dev Upper bound for protocol fee + creator levy on any one swap.
function maxSwapFeeBips() external view returns (uint16);
/// @dev Tightest wallet cap a creator may choose, in bips of supply. Zero = no floor.
function minMaxWalletBips() external view returns (uint16);
/// @dev Tightest per-transfer cap a creator may choose, in bips of supply. Zero = no floor.
function minMaxTxBips() external view returns (uint16);
/// @dev Flat ETH charge per created token.
function launchFee() external view returns (uint256);
// --- catalog & ledger ---
function isApprovedFactory(address factory) external view returns (bool);
/// @dev Stops new creations only; existing markets keep trading.
function launchesPaused() external view returns (bool);
function quoteAsset(address asset) external view returns (PairAsset memory);
/// @dev True only if `asset` is active and of class `class_`.
function isQuoteAssetActive(address asset, AssetClass class_) external view returns (bool);
/// @dev Factory-only. Called right after a token and its market exist.
function recordLaunch(Creation calldata entry) external;
function launchCount() external view returns (uint256);
function launchAt(uint256 index) external view returns (Creation memory);
/// @dev Reverts for tokens that did not come from an allowed factory.
function launchOf(address token) external view returns (Creation memory);
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "none",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@uniswap/v4-core/=node_modules/@uniswap/v4-periphery/lib/v4-core/",
"@uniswap/v4-periphery/=node_modules/@uniswap/v4-periphery/",
"v4-core/=node_modules/@uniswap/v4-periphery/lib/v4-core/",
"v4-periphery/=node_modules/@uniswap/v4-periphery/",
"permit2/=node_modules/@uniswap/v4-periphery/lib/permit2/",
"solmate/=node_modules/@uniswap/v4-periphery/lib/v4-core/lib/solmate/",
"forge-std/=node_modules/@uniswap/v4-periphery/lib/v4-core/lib/forge-std/src/",
"ds-test/=node_modules/@uniswap/v4-periphery/lib/v4-core/lib/forge-std/lib/ds-test/src/",
"openzeppelin-contracts/contracts/=node_modules/@openzeppelin/contracts/",
"@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
"node_modules/@uniswap/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=node_modules/@uniswap/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"/Users/steve/Documents/gweifun/node_modules/@uniswap/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=node_modules/@uniswap/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"/Users/steve/Documents/gweifun/node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"node_modules/@uniswap/v4-periphery/lib/permit2/:openzeppelin-contracts/contracts/=node_modules/@openzeppelin/contracts/",
"/Users/steve/Documents/gweifun/node_modules/@uniswap/v4-periphery/lib/permit2/:openzeppelin-contracts/contracts/=node_modules/@openzeppelin/contracts/",
"node_modules/@uniswap/v4-periphery/lib/permit2/:openzeppelin-contracts/=node_modules/@uniswap/v4-periphery/lib/permit2/lib/openzeppelin-contracts/",
"/Users/steve/Documents/gweifun/node_modules/@uniswap/v4-periphery/lib/permit2/:openzeppelin-contracts/=node_modules/@uniswap/v4-periphery/lib/permit2/lib/openzeppelin-contracts/",
"node_modules/@uniswap/v4-periphery/lib/v4-core/:openzeppelin-contracts/contracts/=node_modules/@openzeppelin/contracts/",
"/Users/steve/Documents/gweifun/node_modules/@uniswap/v4-periphery/lib/v4-core/:openzeppelin-contracts/contracts/=node_modules/@openzeppelin/contracts/",
"node_modules/@uniswap/v4-periphery/lib/v4-core/:openzeppelin-contracts/=node_modules/@uniswap/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"/Users/steve/Documents/gweifun/node_modules/@uniswap/v4-periphery/lib/v4-core/:openzeppelin-contracts/=node_modules/@uniswap/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"node_modules/@uniswap/v4-core/:openzeppelin-contracts/contracts/=node_modules/@openzeppelin/contracts/",
"/Users/steve/Documents/gweifun/node_modules/@uniswap/v4-core/:openzeppelin-contracts/contracts/=node_modules/@openzeppelin/contracts/",
"node_modules/@uniswap/v4-core/:openzeppelin-contracts/=node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/",
"/Users/steve/Documents/gweifun/node_modules/@uniswap/v4-core/:openzeppelin-contracts/=node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/",
"@openzeppelin/=node_modules/@openzeppelin/",
"@uniswap/=node_modules/@uniswap/",
"erc4626-tests/=node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=node_modules/@uniswap/v4-periphery/lib/permit2/lib/forge-gas-snapshot/",
"openzeppelin-contracts/=node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.