Source Code
Overview
ETH Balance
6.928678510933369838 ETH
Token Holdings
More Info
ContractCreator
Multichain Info
N/A
Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
---|---|---|---|---|---|---|---|---|---|
Latest 25 internal transactions (View All)
Advanced mode:
Parent Transaction Hash | Block |
From
|
To
|
|||
---|---|---|---|---|---|---|
7484571 | 2 hrs ago | 0.00099999 ETH | ||||
7484446 | 2 hrs ago | 0.01069852 ETH | ||||
7484404 | 2 hrs ago | 0.001 ETH | ||||
7479145 | 20 hrs ago | 0.00896913 ETH | ||||
7475887 | 31 hrs ago | 0.02 ETH | ||||
7475870 | 31 hrs ago | 0.01 ETH | ||||
7474767 | 35 hrs ago | 0.00175882 ETH | ||||
7467102 | 2 days ago | 0.02235311 ETH | ||||
7466421 | 2 days ago | 0.0002257 ETH | ||||
7466413 | 2 days ago | 0.00186199 ETH | ||||
7464888 | 2 days ago | 0.01854227 ETH | ||||
7464883 | 2 days ago | 0.0936331 ETH | ||||
7464060 | 2 days ago | 0.02 ETH | ||||
7462656 | 3 days ago | 0.09388558 ETH | ||||
7462651 | 3 days ago | 0.01 ETH | ||||
7455664 | 4 days ago | 0 ETH | ||||
7455658 | 4 days ago | 0.001 ETH | ||||
7455654 | 4 days ago | 0.001 ETH | ||||
7451076 | 4 days ago | 0.022038 ETH | ||||
7451062 | 4 days ago | 0.99550907 ETH | ||||
7451060 | 4 days ago | 0.99551113 ETH | ||||
7451057 | 4 days ago | 0.9955132 ETH | ||||
7451040 | 4 days ago | 0.01762922 ETH | ||||
7451030 | 4 days ago | 0.01989441 ETH | ||||
7450966 | 4 days ago | 0.00788991 ETH |
Loading...
Loading
Similar Match Source Code This contract matches the deployed Bytecode of the Source Code for Contract 0xc021A7De...c7Ba2D5d6 The constructor portion of the code might be different and could alter the actual behaviour of the contract
Contract Name:
PoolManager
Compiler Version
v0.8.26+commit.8a97fa7a
Optimization Enabled:
Yes with 44444444 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.24; import {Hooks} from "./libraries/Hooks.sol"; import {Pool} from "./libraries/Pool.sol"; import {SafeCast} from "./libraries/SafeCast.sol"; import {Position} from "./libraries/Position.sol"; import {LPFeeLibrary} from "./libraries/LPFeeLibrary.sol"; import {Currency, CurrencyLibrary} from "./types/Currency.sol"; import {PoolKey} from "./types/PoolKey.sol"; import {TickMath} from "./libraries/TickMath.sol"; import {NoDelegateCall} from "./NoDelegateCall.sol"; import {IHooks} from "./interfaces/IHooks.sol"; import {IPoolManager} from "./interfaces/IPoolManager.sol"; import {IUnlockCallback} from "./interfaces/callback/IUnlockCallback.sol"; import {ProtocolFees} from "./ProtocolFees.sol"; import {ERC6909Claims} from "./ERC6909Claims.sol"; import {PoolId, PoolIdLibrary} from "./types/PoolId.sol"; import {BalanceDelta, BalanceDeltaLibrary, toBalanceDelta} from "./types/BalanceDelta.sol"; import {BeforeSwapDelta} from "./types/BeforeSwapDelta.sol"; import {Lock} from "./libraries/Lock.sol"; import {CurrencyDelta} from "./libraries/CurrencyDelta.sol"; import {NonZeroDeltaCount} from "./libraries/NonZeroDeltaCount.sol"; import {Reserves} from "./libraries/Reserves.sol"; import {Extsload} from "./Extsload.sol"; import {Exttload} from "./Exttload.sol"; import {CustomRevert} from "./libraries/CustomRevert.sol"; // 4 // 44 // 444 // 444 4444 // 4444 4444 4444 // 4444 4444444 4444 4 // 4444 44444444 4444 4 // 44444 4444444 4444444444444444 444444 // 4 44444 44444444 444444444444444444444 4444 // 4 44444 4444444 4444444444444444444444 44444 // 4 444444 4444444 44444444444444444444444 44 4 // 44 44444 444444 444444444444444444444 4 4 // 44 44444 44444 4444444444444444444 4 44 // 44 4444 44 444444444444444 444 // 444 4444 4444444 // 4444444444444 44 4 // 44444444444 444444 444444444 44 // 444444 4444 4444 4444444444 44 // 4444 44 44 4 44444444444 // 44444 444444444 444444444444 4444 // 44444 44444444 4444 44444444 444444 // 44444 4444 444444444 44444444 // 44444 4444 44444444 4444444444 // 44444 4444 444444444 444444444444 // 44444 4444 44444444 444444444444 // 4444444 4444 44444444 4444444 // 4444444 44444 44444444 4444444 // 44444444 44444444444444444444444444444 4444 // 4444444444 44444444444444444444444444444 444 // 444444444444 444444444444444444444444444444 444 444 // 44444444444444 444444444 44444 // 44444 44444444444 444 44444444 444444 // 44444 4444444444 4444444444 444444 44444444 444444444444 // 444444444444444 4444 444444 4444444 44444444 444444444444 // 444444444444444 444 444444 444444 44444444 44444444444 // 4444444444444 4444 444444 4444 4444444444 // 444444444444 4 44444 4444 444444444 // 44444444444 444444 444 44444444 // 44444444 444444 4444 4444444 // 44444 444 44444 // 44444 444 4 4444 // 44444 444 44 444 // 44444 444 4444 // 444444 44444 444 // 444444444 444 // 44444 444 // 444 /// @title PoolManager /// @notice Holds the state for all pools contract PoolManager is IPoolManager, ProtocolFees, NoDelegateCall, ERC6909Claims, Extsload, Exttload { using PoolIdLibrary for PoolKey; using SafeCast for *; using Pool for *; using Hooks for IHooks; using Position for mapping(bytes32 => Position.Info); using CurrencyDelta for Currency; using LPFeeLibrary for uint24; using Reserves for Currency; using CustomRevert for bytes4; /// @inheritdoc IPoolManager int24 public constant MAX_TICK_SPACING = TickMath.MAX_TICK_SPACING; /// @inheritdoc IPoolManager int24 public constant MIN_TICK_SPACING = TickMath.MIN_TICK_SPACING; mapping(PoolId id => Pool.State) internal _pools; constructor(uint256 controllerGasLimit) ProtocolFees(controllerGasLimit) {} /// @notice This will revert if the contract is locked modifier onlyWhenUnlocked() { if (!Lock.isUnlocked()) ManagerLocked.selector.revertWith(); _; } /// @inheritdoc IPoolManager function unlock(bytes calldata data) external override noDelegateCall returns (bytes memory result) { if (Lock.isUnlocked()) AlreadyUnlocked.selector.revertWith(); Lock.unlock(); // the caller does everything in this callback, including paying what they owe via calls to settle result = IUnlockCallback(msg.sender).unlockCallback(data); if (NonZeroDeltaCount.read() != 0) CurrencyNotSettled.selector.revertWith(); Lock.lock(); } /// @inheritdoc IPoolManager function initialize(PoolKey memory key, uint160 sqrtPriceX96, bytes calldata hookData) external override noDelegateCall returns (int24 tick) { // see TickBitmap.sol for overflow conditions that can arise from tick spacing being too large if (key.tickSpacing > MAX_TICK_SPACING) TickSpacingTooLarge.selector.revertWith(); if (key.tickSpacing < MIN_TICK_SPACING) TickSpacingTooSmall.selector.revertWith(); if (key.currency0 >= key.currency1) CurrenciesOutOfOrderOrEqual.selector.revertWith(); if (!key.hooks.isValidHookAddress(key.fee)) Hooks.HookAddressNotValid.selector.revertWith(address(key.hooks)); uint24 lpFee = key.fee.getInitialLPFee(); key.hooks.beforeInitialize(key, sqrtPriceX96, hookData); PoolId id = key.toId(); (, uint24 protocolFee) = _fetchProtocolFee(key); tick = _pools[id].initialize(sqrtPriceX96, protocolFee, lpFee); key.hooks.afterInitialize(key, sqrtPriceX96, tick, hookData); // emit all details of a pool key. poolkeys are not saved in storage and must always be provided by the caller // the key's fee may be a static fee or a sentinel to denote a dynamic fee. emit Initialize(id, key.currency0, key.currency1, key.fee, key.tickSpacing, key.hooks); } /// @inheritdoc IPoolManager function modifyLiquidity( PoolKey memory key, IPoolManager.ModifyLiquidityParams memory params, bytes calldata hookData ) external override onlyWhenUnlocked returns (BalanceDelta callerDelta, BalanceDelta feesAccrued) { PoolId id = key.toId(); Pool.State storage pool = _getPool(id); pool.checkPoolInitialized(); key.hooks.beforeModifyLiquidity(key, params, hookData); BalanceDelta principalDelta; (principalDelta, feesAccrued) = pool.modifyLiquidity( Pool.ModifyLiquidityParams({ owner: msg.sender, tickLower: params.tickLower, tickUpper: params.tickUpper, liquidityDelta: params.liquidityDelta.toInt128(), tickSpacing: key.tickSpacing, salt: params.salt }) ); callerDelta = principalDelta + feesAccrued; // event is emitted before the afterModifyLiquidity call to ensure events are always emitted in order emit ModifyLiquidity(id, msg.sender, params.tickLower, params.tickUpper, params.liquidityDelta); BalanceDelta hookDelta; (callerDelta, hookDelta) = key.hooks.afterModifyLiquidity(key, params, callerDelta, hookData); // if the hook doesnt have the flag to be able to return deltas, hookDelta will always be 0 if (hookDelta != BalanceDeltaLibrary.ZERO_DELTA) _accountPoolBalanceDelta(key, hookDelta, address(key.hooks)); _accountPoolBalanceDelta(key, callerDelta, msg.sender); } /// @inheritdoc IPoolManager function swap(PoolKey memory key, IPoolManager.SwapParams memory params, bytes calldata hookData) external override onlyWhenUnlocked returns (BalanceDelta swapDelta) { if (params.amountSpecified == 0) SwapAmountCannotBeZero.selector.revertWith(); PoolId id = key.toId(); Pool.State storage pool = _getPool(id); pool.checkPoolInitialized(); BeforeSwapDelta beforeSwapDelta; { int256 amountToSwap; uint24 lpFeeOverride; (amountToSwap, beforeSwapDelta, lpFeeOverride) = key.hooks.beforeSwap(key, params, hookData); // execute swap, account protocol fees, and emit swap event // _swap is needed to avoid stack too deep error swapDelta = _swap( pool, id, Pool.SwapParams({ tickSpacing: key.tickSpacing, zeroForOne: params.zeroForOne, amountSpecified: amountToSwap, sqrtPriceLimitX96: params.sqrtPriceLimitX96, lpFeeOverride: lpFeeOverride }), params.zeroForOne ? key.currency0 : key.currency1 // input token ); } BalanceDelta hookDelta; (swapDelta, hookDelta) = key.hooks.afterSwap(key, params, swapDelta, hookData, beforeSwapDelta); // if the hook doesnt have the flag to be able to return deltas, hookDelta will always be 0 if (hookDelta != BalanceDeltaLibrary.ZERO_DELTA) _accountPoolBalanceDelta(key, hookDelta, address(key.hooks)); _accountPoolBalanceDelta(key, swapDelta, msg.sender); } /// @notice Internal swap function to execute a swap, take protocol fees on input token, and emit the swap event function _swap(Pool.State storage pool, PoolId id, Pool.SwapParams memory params, Currency inputCurrency) internal returns (BalanceDelta) { (BalanceDelta delta, uint256 feeForProtocol, uint24 swapFee, Pool.SwapState memory state) = pool.swap(params); // the fee is on the input currency if (feeForProtocol > 0) _updateProtocolFees(inputCurrency, feeForProtocol); // event is emitted before the afterSwap call to ensure events are always emitted in order emit Swap( id, msg.sender, delta.amount0(), delta.amount1(), state.sqrtPriceX96, state.liquidity, state.tick, swapFee ); return delta; } /// @inheritdoc IPoolManager function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData) external override onlyWhenUnlocked returns (BalanceDelta delta) { Pool.State storage pool = _getPool(key.toId()); pool.checkPoolInitialized(); key.hooks.beforeDonate(key, amount0, amount1, hookData); delta = pool.donate(amount0, amount1); _accountPoolBalanceDelta(key, delta, msg.sender); key.hooks.afterDonate(key, amount0, amount1, hookData); } /// @inheritdoc IPoolManager function sync(Currency currency) public returns (uint256 balance) { balance = currency.balanceOfSelf(); currency.setReserves(balance); } /// @inheritdoc IPoolManager function take(Currency currency, address to, uint256 amount) external override onlyWhenUnlocked { unchecked { // negation must be safe as amount is not negative _accountDelta(currency, -(amount.toInt128()), msg.sender); currency.transfer(to, amount); } } /// @inheritdoc IPoolManager function settle(Currency currency) external payable override onlyWhenUnlocked returns (uint256 paid) { if (currency.isNative()) { paid = msg.value; } else { if (msg.value > 0) NonZeroNativeValue.selector.revertWith(); uint256 reservesBefore = currency.getReserves(); uint256 reservesNow = sync(currency); paid = reservesNow - reservesBefore; } _accountDelta(currency, paid.toInt128(), msg.sender); } /// @inheritdoc IPoolManager function mint(address to, uint256 id, uint256 amount) external override onlyWhenUnlocked { unchecked { // negation must be safe as amount is not negative _accountDelta(CurrencyLibrary.fromId(id), -(amount.toInt128()), msg.sender); _mint(to, id, amount); } } /// @inheritdoc IPoolManager function burn(address from, uint256 id, uint256 amount) external override onlyWhenUnlocked { _accountDelta(CurrencyLibrary.fromId(id), amount.toInt128(), msg.sender); _burnFrom(from, id, amount); } /// @inheritdoc IPoolManager function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external { if (!key.fee.isDynamicFee() || msg.sender != address(key.hooks)) { UnauthorizedDynamicLPFeeUpdate.selector.revertWith(); } newDynamicLPFee.validate(); PoolId id = key.toId(); _pools[id].setLPFee(newDynamicLPFee); } /// @notice Adds a balance delta in a currency for a target address function _accountDelta(Currency currency, int128 delta, address target) internal { if (delta == 0) return; int256 current = currency.getDelta(target); int256 next = current + delta; if (next == 0) { NonZeroDeltaCount.decrement(); } else if (current == 0) { NonZeroDeltaCount.increment(); } currency.setDelta(target, next); } /// @notice Accounts the deltas of 2 currencies to a target address function _accountPoolBalanceDelta(PoolKey memory key, BalanceDelta delta, address target) internal { _accountDelta(key.currency0, delta.amount0(), target); _accountDelta(key.currency1, delta.amount1(), target); } /// @notice Implementation of the _getPool function defined in ProtocolFees function _getPool(PoolId id) internal view override returns (Pool.State storage) { return _pools[id]; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {PoolKey} from "../types/PoolKey.sol"; import {IHooks} from "../interfaces/IHooks.sol"; import {SafeCast} from "./SafeCast.sol"; import {LPFeeLibrary} from "./LPFeeLibrary.sol"; import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol"; import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "../types/BeforeSwapDelta.sol"; import {IPoolManager} from "../interfaces/IPoolManager.sol"; import {ParseBytes} from "./ParseBytes.sol"; import {CustomRevert} from "./CustomRevert.sol"; /// @notice V4 decides whether to invoke specific hooks by inspecting the lowest significant bits of the address that /// the hooks contract is deployed to. /// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400 /// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used. library Hooks { using LPFeeLibrary for uint24; using Hooks for IHooks; using SafeCast for int256; using BeforeSwapDeltaLibrary for BeforeSwapDelta; using ParseBytes for bytes; using CustomRevert for bytes4; uint160 internal constant ALL_HOOK_MASK = uint160((1 << 14) - 1); uint160 internal constant BEFORE_INITIALIZE_FLAG = 1 << 13; uint160 internal constant AFTER_INITIALIZE_FLAG = 1 << 12; uint160 internal constant BEFORE_ADD_LIQUIDITY_FLAG = 1 << 11; uint160 internal constant AFTER_ADD_LIQUIDITY_FLAG = 1 << 10; uint160 internal constant BEFORE_REMOVE_LIQUIDITY_FLAG = 1 << 9; uint160 internal constant AFTER_REMOVE_LIQUIDITY_FLAG = 1 << 8; uint160 internal constant BEFORE_SWAP_FLAG = 1 << 7; uint160 internal constant AFTER_SWAP_FLAG = 1 << 6; uint160 internal constant BEFORE_DONATE_FLAG = 1 << 5; uint160 internal constant AFTER_DONATE_FLAG = 1 << 4; uint160 internal constant BEFORE_SWAP_RETURNS_DELTA_FLAG = 1 << 3; uint160 internal constant AFTER_SWAP_RETURNS_DELTA_FLAG = 1 << 2; uint160 internal constant AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 1; uint160 internal constant AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 0; struct Permissions { bool beforeInitialize; bool afterInitialize; bool beforeAddLiquidity; bool afterAddLiquidity; bool beforeRemoveLiquidity; bool afterRemoveLiquidity; bool beforeSwap; bool afterSwap; bool beforeDonate; bool afterDonate; bool beforeSwapReturnDelta; bool afterSwapReturnDelta; bool afterAddLiquidityReturnDelta; bool afterRemoveLiquidityReturnDelta; } /// @notice Thrown if the address will not lead to the specified hook calls being called /// @param hooks The address of the hooks contract error HookAddressNotValid(address hooks); /// @notice Hook did not return its selector error InvalidHookResponse(); /// @notice thrown when a hook call fails error FailedHookCall(); /// @notice The hook's delta changed the swap from exactIn to exactOut or vice versa error HookDeltaExceedsSwapAmount(); /// @notice Utility function intended to be used in hook constructors to ensure /// the deployed hooks address causes the intended hooks to be called /// @param permissions The hooks that are intended to be called /// @dev permissions param is memory as the function will be called from constructors function validateHookPermissions(IHooks self, Permissions memory permissions) internal pure { if ( permissions.beforeInitialize != self.hasPermission(BEFORE_INITIALIZE_FLAG) || permissions.afterInitialize != self.hasPermission(AFTER_INITIALIZE_FLAG) || permissions.beforeAddLiquidity != self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG) || permissions.afterAddLiquidity != self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) || permissions.beforeRemoveLiquidity != self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG) || permissions.afterRemoveLiquidity != self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG) || permissions.beforeSwap != self.hasPermission(BEFORE_SWAP_FLAG) || permissions.afterSwap != self.hasPermission(AFTER_SWAP_FLAG) || permissions.beforeDonate != self.hasPermission(BEFORE_DONATE_FLAG) || permissions.afterDonate != self.hasPermission(AFTER_DONATE_FLAG) || permissions.beforeSwapReturnDelta != self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG) || permissions.afterSwapReturnDelta != self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG) || permissions.afterAddLiquidityReturnDelta != self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG) || permissions.afterRemoveLiquidityReturnDelta != self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG) ) { HookAddressNotValid.selector.revertWith(address(self)); } } /// @notice Ensures that the hook address includes at least one hook flag or dynamic fees, or is the 0 address /// @param self The hook to verify /// @return bool True if the hook address is valid function isValidHookAddress(IHooks self, uint24 fee) internal pure returns (bool) { // The hook can only have a flag to return a hook delta on an action if it also has the corresponding action flag if (!self.hasPermission(BEFORE_SWAP_FLAG) && self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) return false; if (!self.hasPermission(AFTER_SWAP_FLAG) && self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)) return false; if (!self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) && self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)) { return false; } if ( !self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG) && self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG) ) return false; // If there is no hook contract set, then fee cannot be dynamic // If a hook contract is set, it must have at least 1 flag set, or have a dynamic fee return address(self) == address(0) ? !fee.isDynamicFee() : (uint160(address(self)) & ALL_HOOK_MASK > 0 || fee.isDynamicFee()); } /// @notice performs a hook call using the given calldata on the given hook that doesnt return a delta /// @return result The complete data returned by the hook function callHook(IHooks self, bytes memory data) internal returns (bytes memory result) { assembly ("memory-safe") { if iszero(call(gas(), self, 0, add(data, 0x20), mload(data), 0, 0)) { if iszero(returndatasize()) { // if the call failed without a revert reason, revert with `FailedHookCall()` mstore(0, 0x36bc48c5) revert(0x1c, 0x04) } // bubble up revert returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } // allocate result byte array from the free memory pointer result := mload(0x40) // store new free memory pointer at the end of the array padded to 32 bytes mstore(0x40, add(result, and(add(returndatasize(), 0x3f), not(0x1f)))) // store length in memory mstore(result, returndatasize()) // copy return data to result returndatacopy(add(result, 0x20), 0, returndatasize()) } // Check expected selector and returned selector match. if (result.parseSelector() != data.parseSelector()) InvalidHookResponse.selector.revertWith(); } /// @notice performs a hook call using the given calldata on the given hook /// @return delta The delta returned by the hook function callHookWithReturnDelta(IHooks self, bytes memory data, bool parseReturn) internal returns (int256 delta) { bytes memory result = callHook(self, data); // If this hook wasnt meant to return something, default to 0 delta if (!parseReturn) return 0; return result.parseReturnDelta(); } /// @notice modifier to prevent calling a hook if they initiated the action modifier noSelfCall(IHooks self) { if (msg.sender != address(self)) { _; } } /// @notice calls beforeInitialize hook if permissioned and validates return value function beforeInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96, bytes calldata hookData) internal noSelfCall(self) { if (self.hasPermission(BEFORE_INITIALIZE_FLAG)) { self.callHook( abi.encodeWithSelector(IHooks.beforeInitialize.selector, msg.sender, key, sqrtPriceX96, hookData) ); } } /// @notice calls afterInitialize hook if permissioned and validates return value function afterInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96, int24 tick, bytes calldata hookData) internal noSelfCall(self) { if (self.hasPermission(AFTER_INITIALIZE_FLAG)) { self.callHook( abi.encodeWithSelector(IHooks.afterInitialize.selector, msg.sender, key, sqrtPriceX96, tick, hookData) ); } } /// @notice calls beforeModifyLiquidity hook if permissioned and validates return value function beforeModifyLiquidity( IHooks self, PoolKey memory key, IPoolManager.ModifyLiquidityParams memory params, bytes calldata hookData ) internal noSelfCall(self) { if (params.liquidityDelta > 0 && self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)) { self.callHook(abi.encodeWithSelector(IHooks.beforeAddLiquidity.selector, msg.sender, key, params, hookData)); } else if (params.liquidityDelta <= 0 && self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)) { self.callHook( abi.encodeWithSelector(IHooks.beforeRemoveLiquidity.selector, msg.sender, key, params, hookData) ); } } /// @notice calls afterModifyLiquidity hook if permissioned and validates return value function afterModifyLiquidity( IHooks self, PoolKey memory key, IPoolManager.ModifyLiquidityParams memory params, BalanceDelta delta, bytes calldata hookData ) internal returns (BalanceDelta callerDelta, BalanceDelta hookDelta) { if (msg.sender == address(self)) return (delta, BalanceDeltaLibrary.ZERO_DELTA); callerDelta = delta; if (params.liquidityDelta > 0) { if (self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)) { hookDelta = BalanceDelta.wrap( self.callHookWithReturnDelta( abi.encodeCall(IHooks.afterAddLiquidity, (msg.sender, key, params, delta, hookData)), self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG) ) ); callerDelta = callerDelta - hookDelta; } } else { if (self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)) { hookDelta = BalanceDelta.wrap( self.callHookWithReturnDelta( abi.encodeCall(IHooks.afterRemoveLiquidity, (msg.sender, key, params, delta, hookData)), self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG) ) ); callerDelta = callerDelta - hookDelta; } } } /// @notice calls beforeSwap hook if permissioned and validates return value function beforeSwap(IHooks self, PoolKey memory key, IPoolManager.SwapParams memory params, bytes calldata hookData) internal returns (int256 amountToSwap, BeforeSwapDelta hookReturn, uint24 lpFeeOverride) { amountToSwap = params.amountSpecified; if (msg.sender == address(self)) return (amountToSwap, BeforeSwapDeltaLibrary.ZERO_DELTA, lpFeeOverride); if (self.hasPermission(BEFORE_SWAP_FLAG)) { bytes memory result = callHook(self, abi.encodeCall(IHooks.beforeSwap, (msg.sender, key, params, hookData))); // dynamic fee pools that do not want to override the cache fee, return 0 otherwise they return a valid fee with the override flag if (key.fee.isDynamicFee()) lpFeeOverride = result.parseFee(); // skip this logic for the case where the hook return is 0 if (self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) { hookReturn = BeforeSwapDelta.wrap(result.parseReturnDelta()); // any return in unspecified is passed to the afterSwap hook for handling int128 hookDeltaSpecified = hookReturn.getSpecifiedDelta(); // Update the swap amount according to the hook's return, and check that the swap type doesnt change (exact input/output) if (hookDeltaSpecified != 0) { bool exactInput = amountToSwap < 0; amountToSwap += hookDeltaSpecified; if (exactInput ? amountToSwap > 0 : amountToSwap < 0) { HookDeltaExceedsSwapAmount.selector.revertWith(); } } } } } /// @notice calls afterSwap hook if permissioned and validates return value function afterSwap( IHooks self, PoolKey memory key, IPoolManager.SwapParams memory params, BalanceDelta swapDelta, bytes calldata hookData, BeforeSwapDelta beforeSwapHookReturn ) internal returns (BalanceDelta, BalanceDelta) { if (msg.sender == address(self)) return (swapDelta, BalanceDeltaLibrary.ZERO_DELTA); int128 hookDeltaSpecified = beforeSwapHookReturn.getSpecifiedDelta(); int128 hookDeltaUnspecified = beforeSwapHookReturn.getUnspecifiedDelta(); if (self.hasPermission(AFTER_SWAP_FLAG)) { hookDeltaUnspecified += self.callHookWithReturnDelta( abi.encodeCall(IHooks.afterSwap, (msg.sender, key, params, swapDelta, hookData)), self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG) ).toInt128(); } BalanceDelta hookDelta; if (hookDeltaUnspecified != 0 || hookDeltaSpecified != 0) { hookDelta = (params.amountSpecified < 0 == params.zeroForOne) ? toBalanceDelta(hookDeltaSpecified, hookDeltaUnspecified) : toBalanceDelta(hookDeltaUnspecified, hookDeltaSpecified); // the caller has to pay for (or receive) the hook's delta swapDelta = swapDelta - hookDelta; } return (swapDelta, hookDelta); } /// @notice calls beforeDonate hook if permissioned and validates return value function beforeDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData) internal noSelfCall(self) { if (self.hasPermission(BEFORE_DONATE_FLAG)) { self.callHook( abi.encodeWithSelector(IHooks.beforeDonate.selector, msg.sender, key, amount0, amount1, hookData) ); } } /// @notice calls afterDonate hook if permissioned and validates return value function afterDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData) internal noSelfCall(self) { if (self.hasPermission(AFTER_DONATE_FLAG)) { self.callHook( abi.encodeWithSelector(IHooks.afterDonate.selector, msg.sender, key, amount0, amount1, hookData) ); } } function hasPermission(IHooks self, uint160 flag) internal pure returns (bool) { return uint160(address(self)) & flag != 0; } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.20; import {SafeCast} from "./SafeCast.sol"; import {TickBitmap} from "./TickBitmap.sol"; import {Position} from "./Position.sol"; import {FullMath} from "./FullMath.sol"; import {FixedPoint128} from "./FixedPoint128.sol"; import {TickMath} from "./TickMath.sol"; import {SqrtPriceMath} from "./SqrtPriceMath.sol"; import {SwapMath} from "./SwapMath.sol"; import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol"; import {Slot0} from "../types/Slot0.sol"; import {ProtocolFeeLibrary} from "./ProtocolFeeLibrary.sol"; import {LiquidityMath} from "./LiquidityMath.sol"; import {LPFeeLibrary} from "./LPFeeLibrary.sol"; import {CustomRevert} from "./CustomRevert.sol"; library Pool { using SafeCast for *; using TickBitmap for mapping(int16 => uint256); using Position for mapping(bytes32 => Position.Info); using Position for Position.Info; using Pool for State; using ProtocolFeeLibrary for uint24; using LPFeeLibrary for uint24; using CustomRevert for bytes4; /// @notice Thrown when tickLower is not below tickUpper /// @param tickLower The invalid tickLower /// @param tickUpper The invalid tickUpper error TicksMisordered(int24 tickLower, int24 tickUpper); /// @notice Thrown when tickLower is less than min tick /// @param tickLower The invalid tickLower error TickLowerOutOfBounds(int24 tickLower); /// @notice Thrown when tickUpper exceeds max tick /// @param tickUpper The invalid tickUpper error TickUpperOutOfBounds(int24 tickUpper); /// @notice For the tick spacing, the tick has too much liquidity error TickLiquidityOverflow(int24 tick); /// @notice Thrown when interacting with an uninitialized tick that must be initialized /// @param tick The uninitialized tick error TickNotInitialized(int24 tick); /// @notice Thrown when trying to initialize an already initialized pool error PoolAlreadyInitialized(); /// @notice Thrown when trying to interact with a non-initialized pool error PoolNotInitialized(); /// @notice Thrown when sqrtPriceLimitX96 on a swap has already exceeded its limit /// @param sqrtPriceCurrentX96 The invalid, already surpassed sqrtPriceLimitX96 /// @param sqrtPriceLimitX96 The surpassed price limit error PriceLimitAlreadyExceeded(uint160 sqrtPriceCurrentX96, uint160 sqrtPriceLimitX96); /// @notice Thrown when sqrtPriceLimitX96 lies outside of valid tick/price range /// @param sqrtPriceLimitX96 The invalid, out-of-bounds sqrtPriceLimitX96 error PriceLimitOutOfBounds(uint160 sqrtPriceLimitX96); /// @notice Thrown by donate if there is currently 0 liquidity, since the fees will not go to any liquidity providers error NoLiquidityToReceiveFees(); /// @notice Thrown when trying to swap with max lp fee and specifying an output amount error InvalidFeeForExactOut(); // info stored for each initialized individual tick struct TickInfo { // the total position liquidity that references this tick uint128 liquidityGross; // amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left), int128 liquidityNet; // fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) // only has relative meaning, not absolute — the value depends on when the tick is initialized uint256 feeGrowthOutside0X128; uint256 feeGrowthOutside1X128; } /// @dev The state of a pool struct State { Slot0 slot0; uint256 feeGrowthGlobal0X128; uint256 feeGrowthGlobal1X128; uint128 liquidity; mapping(int24 => TickInfo) ticks; mapping(int16 => uint256) tickBitmap; mapping(bytes32 => Position.Info) positions; } /// @dev Common checks for valid tick inputs. function checkTicks(int24 tickLower, int24 tickUpper) private pure { if (tickLower >= tickUpper) TicksMisordered.selector.revertWith(tickLower, tickUpper); if (tickLower < TickMath.MIN_TICK) TickLowerOutOfBounds.selector.revertWith(tickLower); if (tickUpper > TickMath.MAX_TICK) TickUpperOutOfBounds.selector.revertWith(tickUpper); } function initialize(State storage self, uint160 sqrtPriceX96, uint24 protocolFee, uint24 lpFee) internal returns (int24 tick) { if (self.slot0.sqrtPriceX96() != 0) PoolAlreadyInitialized.selector.revertWith(); tick = TickMath.getTickAtSqrtPrice(sqrtPriceX96); self.slot0 = Slot0.wrap(bytes32(0)).setSqrtPriceX96(sqrtPriceX96).setTick(tick).setProtocolFee(protocolFee) .setLpFee(lpFee); } function setProtocolFee(State storage self, uint24 protocolFee) internal { self.checkPoolInitialized(); self.slot0 = self.slot0.setProtocolFee(protocolFee); } /// @notice Only dynamic fee pools may update the lp fee. function setLPFee(State storage self, uint24 lpFee) internal { self.checkPoolInitialized(); self.slot0 = self.slot0.setLpFee(lpFee); } struct ModifyLiquidityParams { // the address that owns the position address owner; // the lower and upper tick of the position int24 tickLower; int24 tickUpper; // any change in liquidity int128 liquidityDelta; // the spacing between ticks int24 tickSpacing; // used to distinguish positions of the same owner, at the same tick range bytes32 salt; } struct ModifyLiquidityState { bool flippedLower; uint128 liquidityGrossAfterLower; bool flippedUpper; uint128 liquidityGrossAfterUpper; } /// @notice Effect changes to a position in a pool /// @dev PoolManager checks that the pool is initialized before calling /// @param params the position details and the change to the position's liquidity to effect /// @return delta the deltas of the token balances of the pool, from the liquidity change /// @return feeDelta the fees generated by the liquidity range function modifyLiquidity(State storage self, ModifyLiquidityParams memory params) internal returns (BalanceDelta delta, BalanceDelta feeDelta) { int128 liquidityDelta = params.liquidityDelta; int24 tickLower = params.tickLower; int24 tickUpper = params.tickUpper; checkTicks(tickLower, tickUpper); { ModifyLiquidityState memory state; // if we need to update the ticks, do it if (liquidityDelta != 0) { (state.flippedLower, state.liquidityGrossAfterLower) = updateTick(self, tickLower, liquidityDelta, false); (state.flippedUpper, state.liquidityGrossAfterUpper) = updateTick(self, tickUpper, liquidityDelta, true); // `>` and `>=` are logically equivalent here but `>=` is cheaper if (liquidityDelta >= 0) { uint128 maxLiquidityPerTick = tickSpacingToMaxLiquidityPerTick(params.tickSpacing); if (state.liquidityGrossAfterLower > maxLiquidityPerTick) { TickLiquidityOverflow.selector.revertWith(tickLower); } if (state.liquidityGrossAfterUpper > maxLiquidityPerTick) { TickLiquidityOverflow.selector.revertWith(tickUpper); } } if (state.flippedLower) { self.tickBitmap.flipTick(tickLower, params.tickSpacing); } if (state.flippedUpper) { self.tickBitmap.flipTick(tickUpper, params.tickSpacing); } } { (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) = getFeeGrowthInside(self, tickLower, tickUpper); Position.Info storage position = self.positions.get(params.owner, tickLower, tickUpper, params.salt); (uint256 feesOwed0, uint256 feesOwed1) = position.update(liquidityDelta, feeGrowthInside0X128, feeGrowthInside1X128); // Fees earned from LPing are added to the user's currency delta. feeDelta = toBalanceDelta(feesOwed0.toInt128(), feesOwed1.toInt128()); } // clear any tick data that is no longer needed if (liquidityDelta < 0) { if (state.flippedLower) { clearTick(self, tickLower); } if (state.flippedUpper) { clearTick(self, tickUpper); } } } if (liquidityDelta != 0) { Slot0 _slot0 = self.slot0; (int24 tick, uint160 sqrtPriceX96) = (_slot0.tick(), _slot0.sqrtPriceX96()); if (tick < tickLower) { // current tick is below the passed range; liquidity can only become in range by crossing from left to // right, when we'll need _more_ currency0 (it's becoming more valuable) so user must provide it delta = toBalanceDelta( SqrtPriceMath.getAmount0Delta( TickMath.getSqrtPriceAtTick(tickLower), TickMath.getSqrtPriceAtTick(tickUpper), liquidityDelta ).toInt128(), 0 ); } else if (tick < tickUpper) { delta = toBalanceDelta( SqrtPriceMath.getAmount0Delta(sqrtPriceX96, TickMath.getSqrtPriceAtTick(tickUpper), liquidityDelta) .toInt128(), SqrtPriceMath.getAmount1Delta(TickMath.getSqrtPriceAtTick(tickLower), sqrtPriceX96, liquidityDelta) .toInt128() ); self.liquidity = LiquidityMath.addDelta(self.liquidity, liquidityDelta); } else { // current tick is above the passed range; liquidity can only become in range by crossing from right to // left, when we'll need _more_ currency1 (it's becoming more valuable) so user must provide it delta = toBalanceDelta( 0, SqrtPriceMath.getAmount1Delta( TickMath.getSqrtPriceAtTick(tickLower), TickMath.getSqrtPriceAtTick(tickUpper), liquidityDelta ).toInt128() ); } } } // the top level state of the swap, the results of which are recorded in storage at the end struct SwapState { // the amount remaining to be swapped in/out of the input/output asset int256 amountSpecifiedRemaining; // the amount already swapped out/in of the output/input asset int256 amountCalculated; // current sqrt(price) uint160 sqrtPriceX96; // the tick associated with the current price int24 tick; // the global fee growth of the input token uint256 feeGrowthGlobalX128; // the current liquidity in range uint128 liquidity; } struct StepComputations { // the price at the beginning of the step uint160 sqrtPriceStartX96; // the next tick to swap to from the current tick in the swap direction int24 tickNext; // whether tickNext is initialized or not bool initialized; // sqrt(price) for the next tick (1/0) uint160 sqrtPriceNextX96; // how much is being swapped in in this step uint256 amountIn; // how much is being swapped out uint256 amountOut; // how much fee is being paid in uint256 feeAmount; } struct SwapParams { int24 tickSpacing; bool zeroForOne; int256 amountSpecified; uint160 sqrtPriceLimitX96; uint24 lpFeeOverride; } /// @notice Executes a swap against the state, and returns the amount deltas of the pool /// @dev PoolManager checks that the pool is initialized before calling function swap(State storage self, SwapParams memory params) internal returns (BalanceDelta result, uint256 feeForProtocol, uint24 swapFee, SwapState memory state) { Slot0 slot0Start = self.slot0; bool zeroForOne = params.zeroForOne; uint128 liquidityStart = self.liquidity; uint256 protocolFee = zeroForOne ? slot0Start.protocolFee().getZeroForOneFee() : slot0Start.protocolFee().getOneForZeroFee(); state.amountSpecifiedRemaining = params.amountSpecified; state.amountCalculated = 0; state.sqrtPriceX96 = slot0Start.sqrtPriceX96(); state.tick = slot0Start.tick(); state.feeGrowthGlobalX128 = zeroForOne ? self.feeGrowthGlobal0X128 : self.feeGrowthGlobal1X128; state.liquidity = liquidityStart; // if the beforeSwap hook returned a valid fee override, use that as the LP fee, otherwise load from storage { uint24 lpFee = params.lpFeeOverride.isOverride() ? params.lpFeeOverride.removeOverrideFlagAndValidate() : slot0Start.lpFee(); swapFee = protocolFee == 0 ? lpFee : uint24(protocolFee).calculateSwapFee(lpFee); } bool exactInput = params.amountSpecified < 0; if (!exactInput && (swapFee == LPFeeLibrary.MAX_LP_FEE)) { InvalidFeeForExactOut.selector.revertWith(); } if (params.amountSpecified == 0) return (BalanceDeltaLibrary.ZERO_DELTA, 0, swapFee, state); if (zeroForOne) { if (params.sqrtPriceLimitX96 >= slot0Start.sqrtPriceX96()) { PriceLimitAlreadyExceeded.selector.revertWith(slot0Start.sqrtPriceX96(), params.sqrtPriceLimitX96); } if (params.sqrtPriceLimitX96 <= TickMath.MIN_SQRT_PRICE) { PriceLimitOutOfBounds.selector.revertWith(params.sqrtPriceLimitX96); } } else { if (params.sqrtPriceLimitX96 <= slot0Start.sqrtPriceX96()) { PriceLimitAlreadyExceeded.selector.revertWith(slot0Start.sqrtPriceX96(), params.sqrtPriceLimitX96); } if (params.sqrtPriceLimitX96 >= TickMath.MAX_SQRT_PRICE) { PriceLimitOutOfBounds.selector.revertWith(params.sqrtPriceLimitX96); } } StepComputations memory step; // continue swapping as long as we haven't used the entire input/output and haven't reached the price limit while (!(state.amountSpecifiedRemaining == 0 || state.sqrtPriceX96 == params.sqrtPriceLimitX96)) { step.sqrtPriceStartX96 = state.sqrtPriceX96; (step.tickNext, step.initialized) = self.tickBitmap.nextInitializedTickWithinOneWord(state.tick, params.tickSpacing, zeroForOne); // ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds if (step.tickNext <= TickMath.MIN_TICK) { step.tickNext = TickMath.MIN_TICK; } if (step.tickNext >= TickMath.MAX_TICK) { step.tickNext = TickMath.MAX_TICK; } // get the price for the next tick step.sqrtPriceNextX96 = TickMath.getSqrtPriceAtTick(step.tickNext); // compute values to swap to the target tick, price limit, or point where input/output amount is exhausted (state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath.computeSwapStep( state.sqrtPriceX96, SwapMath.getSqrtPriceTarget(zeroForOne, step.sqrtPriceNextX96, params.sqrtPriceLimitX96), state.liquidity, state.amountSpecifiedRemaining, swapFee ); if (!exactInput) { unchecked { state.amountSpecifiedRemaining -= step.amountOut.toInt256(); } state.amountCalculated = state.amountCalculated - (step.amountIn + step.feeAmount).toInt256(); } else { // safe because we test that amountSpecified > amountIn + feeAmount in SwapMath unchecked { state.amountSpecifiedRemaining += (step.amountIn + step.feeAmount).toInt256(); } state.amountCalculated = state.amountCalculated + step.amountOut.toInt256(); } // if the protocol fee is on, calculate how much is owed, decrement feeAmount, and increment protocolFee if (protocolFee > 0) { unchecked { // step.amountIn does not include the swap fee, as it's already been taken from it, // so add it back to get the total amountIn and use that to calculate the amount of fees owed to the protocol uint256 delta = (step.amountIn + step.feeAmount) * protocolFee / ProtocolFeeLibrary.PIPS_DENOMINATOR; // subtract it from the total fee and add it to the protocol fee step.feeAmount -= delta; feeForProtocol += delta; } } // update global fee tracker if (state.liquidity > 0) { unchecked { state.feeGrowthGlobalX128 += FullMath.mulDiv(step.feeAmount, FixedPoint128.Q128, state.liquidity); } } // shift tick if we reached the next price if (state.sqrtPriceX96 == step.sqrtPriceNextX96) { // if the tick is initialized, run the tick transition if (step.initialized) { (uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = zeroForOne ? (state.feeGrowthGlobalX128, self.feeGrowthGlobal1X128) : (self.feeGrowthGlobal0X128, state.feeGrowthGlobalX128); int128 liquidityNet = Pool.crossTick(self, step.tickNext, feeGrowthGlobal0X128, feeGrowthGlobal1X128); // if we're moving leftward, we interpret liquidityNet as the opposite sign // safe because liquidityNet cannot be type(int128).min unchecked { if (zeroForOne) liquidityNet = -liquidityNet; } state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet); } // Equivalent to `state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;` unchecked { // cannot cast a bool to an int24 in Solidity int24 _zeroForOne; assembly { _zeroForOne := zeroForOne } state.tick = step.tickNext - _zeroForOne; } } else if (state.sqrtPriceX96 != step.sqrtPriceStartX96) { // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved state.tick = TickMath.getTickAtSqrtPrice(state.sqrtPriceX96); } } self.slot0 = slot0Start.setTick(state.tick).setSqrtPriceX96(state.sqrtPriceX96); // update liquidity if it changed if (liquidityStart != state.liquidity) self.liquidity = state.liquidity; // update fee growth global if (!zeroForOne) { self.feeGrowthGlobal1X128 = state.feeGrowthGlobalX128; } else { self.feeGrowthGlobal0X128 = state.feeGrowthGlobalX128; } unchecked { if (zeroForOne != exactInput) { result = toBalanceDelta( state.amountCalculated.toInt128(), (params.amountSpecified - state.amountSpecifiedRemaining).toInt128() ); } else { result = toBalanceDelta( (params.amountSpecified - state.amountSpecifiedRemaining).toInt128(), state.amountCalculated.toInt128() ); } } } /// @notice Donates the given amount of currency0 and currency1 to the pool function donate(State storage state, uint256 amount0, uint256 amount1) internal returns (BalanceDelta delta) { uint128 liquidity = state.liquidity; if (liquidity == 0) NoLiquidityToReceiveFees.selector.revertWith(); unchecked { // negation safe as amount0 and amount1 are always positive delta = toBalanceDelta(-(amount0.toInt128()), -(amount1.toInt128())); if (amount0 > 0) { state.feeGrowthGlobal0X128 += FullMath.mulDiv(amount0, FixedPoint128.Q128, liquidity); } if (amount1 > 0) { state.feeGrowthGlobal1X128 += FullMath.mulDiv(amount1, FixedPoint128.Q128, liquidity); } } } /// @notice Retrieves fee growth data /// @param self The Pool state struct /// @param tickLower The lower tick boundary of the position /// @param tickUpper The upper tick boundary of the position /// @return feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries /// @return feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries function getFeeGrowthInside(State storage self, int24 tickLower, int24 tickUpper) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) { TickInfo storage lower = self.ticks[tickLower]; TickInfo storage upper = self.ticks[tickUpper]; int24 tickCurrent = self.slot0.tick(); unchecked { if (tickCurrent < tickLower) { feeGrowthInside0X128 = lower.feeGrowthOutside0X128 - upper.feeGrowthOutside0X128; feeGrowthInside1X128 = lower.feeGrowthOutside1X128 - upper.feeGrowthOutside1X128; } else if (tickCurrent >= tickUpper) { feeGrowthInside0X128 = upper.feeGrowthOutside0X128 - lower.feeGrowthOutside0X128; feeGrowthInside1X128 = upper.feeGrowthOutside1X128 - lower.feeGrowthOutside1X128; } else { feeGrowthInside0X128 = self.feeGrowthGlobal0X128 - lower.feeGrowthOutside0X128 - upper.feeGrowthOutside0X128; feeGrowthInside1X128 = self.feeGrowthGlobal1X128 - lower.feeGrowthOutside1X128 - upper.feeGrowthOutside1X128; } } } /// @notice Updates a tick and returns true if the tick was flipped from initialized to uninitialized, or vice versa /// @param self The mapping containing all tick information for initialized ticks /// @param tick The tick that will be updated /// @param liquidityDelta A new amount of liquidity to be added (subtracted) when tick is crossed from left to right (right to left) /// @param upper true for updating a position's upper tick, or false for updating a position's lower tick /// @return flipped Whether the tick was flipped from initialized to uninitialized, or vice versa /// @return liquidityGrossAfter The total amount of liquidity for all positions that references the tick after the update function updateTick(State storage self, int24 tick, int128 liquidityDelta, bool upper) internal returns (bool flipped, uint128 liquidityGrossAfter) { TickInfo storage info = self.ticks[tick]; uint128 liquidityGrossBefore; int128 liquidityNetBefore; assembly { // load first slot of info which contains liquidityGross and liquidityNet packed // where the top 128 bits are liquidityNet and the bottom 128 bits are liquidityGross let liquidity := sload(info.slot) // slice off top 128 bits of liquidity (liquidityNet) to get just liquidityGross liquidityGrossBefore := shr(128, shl(128, liquidity)) // signed shift right 128 bits to get just liquidityNet liquidityNetBefore := sar(128, liquidity) } liquidityGrossAfter = LiquidityMath.addDelta(liquidityGrossBefore, liquidityDelta); flipped = (liquidityGrossAfter == 0) != (liquidityGrossBefore == 0); if (liquidityGrossBefore == 0) { // by convention, we assume that all growth before a tick was initialized happened _below_ the tick if (tick <= self.slot0.tick()) { info.feeGrowthOutside0X128 = self.feeGrowthGlobal0X128; info.feeGrowthOutside1X128 = self.feeGrowthGlobal1X128; } } // when the lower (upper) tick is crossed left to right (right to left), liquidity must be added (removed) int128 liquidityNet = upper ? liquidityNetBefore - liquidityDelta : liquidityNetBefore + liquidityDelta; assembly { // liquidityGrossAfter and liquidityNet are packed in the first slot of `info` // So we can store them with a single sstore by packing them ourselves first sstore( info.slot, // bitwise OR to pack liquidityGrossAfter and liquidityNet or( // liquidityGross is in the low bits, upper bits are already 0 liquidityGrossAfter, // shift liquidityNet to take the upper bits and lower bits get filled with 0 shl(128, liquidityNet) ) ) } } /// @notice Derives max liquidity per tick from given tick spacing /// @dev Executed within the pool constructor /// @param tickSpacing The amount of required tick separation, realized in multiples of `tickSpacing` /// e.g., a tickSpacing of 3 requires ticks to be initialized every 3rd tick i.e., ..., -6, -3, 0, 3, 6, ... /// @return result The max liquidity per tick function tickSpacingToMaxLiquidityPerTick(int24 tickSpacing) internal pure returns (uint128 result) { // Equivalent to: // int24 minTick = (TickMath.MIN_TICK / tickSpacing) * tickSpacing; // int24 maxTick = (TickMath.MAX_TICK / tickSpacing) * tickSpacing; // uint24 numTicks = uint24((maxTick - minTick) / tickSpacing) + 1; // return type(uint128).max / numTicks; int24 MAX_TICK = TickMath.MAX_TICK; int24 MIN_TICK = TickMath.MIN_TICK; // tick spacing will never be 0 since TickMath.MIN_TICK_SPACING is 1 assembly { let minTick := mul(sdiv(MIN_TICK, tickSpacing), tickSpacing) let maxTick := mul(sdiv(MAX_TICK, tickSpacing), tickSpacing) let numTicks := add(sdiv(sub(maxTick, minTick), tickSpacing), 1) result := div(sub(shl(128, 1), 1), numTicks) } } /// @notice Reverts if the given pool has not been initialized function checkPoolInitialized(State storage self) internal view { if (self.slot0.sqrtPriceX96() == 0) PoolNotInitialized.selector.revertWith(); } /// @notice Clears tick data /// @param self The mapping containing all initialized tick information for initialized ticks /// @param tick The tick that will be cleared function clearTick(State storage self, int24 tick) internal { delete self.ticks[tick]; } /// @notice Transitions to next tick as needed by price movement /// @param self The Pool state struct /// @param tick The destination tick of the transition /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0 /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1 /// @return liquidityNet The amount of liquidity added (subtracted) when tick is crossed from left to right (right to left) function crossTick(State storage self, int24 tick, uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) internal returns (int128 liquidityNet) { unchecked { TickInfo storage info = self.ticks[tick]; info.feeGrowthOutside0X128 = feeGrowthGlobal0X128 - info.feeGrowthOutside0X128; info.feeGrowthOutside1X128 = feeGrowthGlobal1X128 - info.feeGrowthOutside1X128; liquidityNet = info.liquidityNet; } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { error SafeCastOverflow(); function _revertOverflow() private pure { assembly ("memory-safe") { // Store the function selector of `SafeCastOverflow()`. mstore(0x00, 0x93dafdf1) // Revert with (offset, size). revert(0x1c, 0x04) } } /// @notice Cast a uint256 to a uint160, revert on overflow /// @param x The uint256 to be downcasted /// @return The downcasted integer, now type uint160 function toUint160(uint256 x) internal pure returns (uint160) { if (x >= 1 << 160) _revertOverflow(); return uint160(x); } /// @notice Cast a uint256 to a uint128, revert on overflow /// @param x The uint256 to be downcasted /// @return The downcasted integer, now type uint128 function toUint128(uint256 x) internal pure returns (uint128) { if (x >= 1 << 128) _revertOverflow(); return uint128(x); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param x The int256 to be downcasted /// @return The downcasted integer, now type int128 function toInt128(int256 x) internal pure returns (int128) { unchecked { if (((1 << 127) + uint256(x)) >> 128 == uint256(0)) return int128(x); _revertOverflow(); } } /// @notice Cast a uint256 to a int256, revert on overflow /// @param x The uint256 to be casted /// @return The casted integer, now type int256 function toInt256(uint256 x) internal pure returns (int256) { if (int256(x) >= 0) return int256(x); _revertOverflow(); } /// @notice Cast a uint256 to a int128, revert on overflow /// @param x The uint256 to be downcasted /// @return The downcasted integer, now type int128 function toInt128(uint256 x) internal pure returns (int128) { if (x >= 1 << 127) _revertOverflow(); return int128(int256(x)); } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.20; import {FullMath} from "./FullMath.sol"; import {FixedPoint128} from "./FixedPoint128.sol"; import {LiquidityMath} from "./LiquidityMath.sol"; import {CustomRevert} from "./CustomRevert.sol"; /// @title Position /// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary /// @dev Positions store additional state for tracking fees owed to the position library Position { using CustomRevert for bytes4; /// @notice Cannot update a position with no liquidity error CannotUpdateEmptyPosition(); // info stored for each user's position struct Info { // the amount of liquidity owned by this position uint128 liquidity; // fee growth per unit of liquidity as of the last update to liquidity or fees owed uint256 feeGrowthInside0LastX128; uint256 feeGrowthInside1LastX128; } /// @notice Returns the Info struct of a position, given an owner and position boundaries /// @param self The mapping containing all user positions /// @param owner The address of the position owner /// @param tickLower The lower tick boundary of the position /// @param tickUpper The upper tick boundary of the position /// @param salt A unique value to differentiate between multiple positions in the same range /// @return position The position info struct of the given owners' position function get(mapping(bytes32 => Info) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt) internal view returns (Info storage position) { // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt)) bytes32 positionKey; assembly ("memory-safe") { mstore(0x26, salt) // [0x26, 0x46) mstore(0x06, tickUpper) // [0x23, 0x26) mstore(0x03, tickLower) // [0x20, 0x23) mstore(0, owner) // [0x0c, 0x20) positionKey := keccak256(0x0c, 0x3a) // len is 58 bytes mstore(0x26, 0) // rewrite 0x26 to 0 } position = self[positionKey]; } /// @notice Credits accumulated fees to a user's position /// @param self The individual position to update /// @param liquidityDelta The change in pool liquidity as a result of the position update /// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries /// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries /// @return feesOwed0 The amount of currency0 owed to the position owner /// @return feesOwed1 The amount of currency1 owed to the position owner function update( Info storage self, int128 liquidityDelta, uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128 ) internal returns (uint256 feesOwed0, uint256 feesOwed1) { uint128 liquidity = self.liquidity; if (liquidityDelta == 0) { // disallow pokes for 0 liquidity positions if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith(); } else { self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta); } // calculate accumulated fees. overflow in the subtraction of fee growth is expected unchecked { feesOwed0 = FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128); feesOwed1 = FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128); } // update the position self.feeGrowthInside0LastX128 = feeGrowthInside0X128; self.feeGrowthInside1LastX128 = feeGrowthInside1X128; } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; import {PoolKey} from "../types/PoolKey.sol"; import {CustomRevert} from "./CustomRevert.sol"; library LPFeeLibrary { using LPFeeLibrary for uint24; using CustomRevert for bytes4; /// @notice Thrown when the static or dynamic fee on a pool exceeds 100%. error FeeTooLarge(); // an lp fee of exactly 0b1000000... signals a dynamic fee pool. This isnt a valid static fee as it is > MAX_LP_FEE uint24 public constant DYNAMIC_FEE_FLAG = 0x800000; // the second bit of the fee returned by beforeSwap is used to signal if the stored LP fee should be overridden in this swap // only dynamic-fee pools can return a fee via the beforeSwap hook uint24 public constant OVERRIDE_FEE_FLAG = 0x400000; // mask to remove the override fee flag from a fee returned by the beforeSwaphook uint24 public constant REMOVE_OVERRIDE_MASK = 0xBFFFFF; // the lp fee is represented in hundredths of a bip, so the max is 100% uint24 public constant MAX_LP_FEE = 1000000; /// @notice returns true if a pool's LP fee signals that the pool has a dynamic fee function isDynamicFee(uint24 self) internal pure returns (bool) { return self == DYNAMIC_FEE_FLAG; } /// @notice returns true if an LP fee is valid, aka not above the maxmimum permitted fee function isValid(uint24 self) internal pure returns (bool) { return self <= MAX_LP_FEE; } /// @notice validates whether an LP fee is larger than the maximum, and reverts if invalid function validate(uint24 self) internal pure { if (!self.isValid()) FeeTooLarge.selector.revertWith(); } /// @notice gets and validates the initial LP fee for a pool. Dynamic fee pools have an initial fee of 0. /// @dev if a dynamic fee pool wants a non-0 initial fee, it should call `updateDynamicLPFee` in the afterInitialize hook function getInitialLPFee(uint24 self) internal pure returns (uint24) { // the initial fee for a dynamic fee pool is 0 if (self.isDynamicFee()) return 0; self.validate(); return self; } /// @notice returns true if the fee has the override flag set (top bit of the uint24) function isOverride(uint24 self) internal pure returns (bool) { return self & OVERRIDE_FEE_FLAG != 0; } /// @notice returns a fee with the override flag removed function removeOverrideFlag(uint24 self) internal pure returns (uint24) { return self & REMOVE_OVERRIDE_MASK; } /// @notice Removes the override flag and validates the fee (reverts if the fee is too large) function removeOverrideFlagAndValidate(uint24 self) internal pure returns (uint24 fee) { fee = self.removeOverrideFlag(); fee.validate(); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol"; type Currency is address; using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global; using CurrencyLibrary for Currency global; function equals(Currency currency, Currency other) pure returns (bool) { return Currency.unwrap(currency) == Currency.unwrap(other); } function greaterThan(Currency currency, Currency other) pure returns (bool) { return Currency.unwrap(currency) > Currency.unwrap(other); } function lessThan(Currency currency, Currency other) pure returns (bool) { return Currency.unwrap(currency) < Currency.unwrap(other); } function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) { return Currency.unwrap(currency) >= Currency.unwrap(other); } /// @title CurrencyLibrary /// @dev This library allows for transferring and holding native tokens and ERC20 tokens library CurrencyLibrary { /// @notice Thrown when a native transfer fails error NativeTransferFailed(); /// @notice Thrown when an ERC20 transfer fails error ERC20TransferFailed(); Currency public constant NATIVE = Currency.wrap(address(0)); function transfer(Currency currency, address to, uint256 amount) internal { // altered from https://github.com/Vectorized/solady/blob/89101d53b7c8784cca935c1f2f6403639cee48b2/src/utils/SafeTransferLib.sol // modified custom error selectors if (currency.isNative()) { assembly ("memory-safe") { // Transfer the ETH and revert if it fails. if iszero(call(gas(), to, amount, 0x00, 0x00, 0x00, 0x00)) { mstore(0x00, 0xf4b3b1bc) // `NativeTransferFailed()`. revert(0x1c, 0x04) } } } else { assembly ("memory-safe") { mstore(0x14, to) // Store the `to` address in [0x20, 0x34). mstore(0x34, amount) // Store the `amount` argument in [0x34, 0x54). // Store the selector of `transfer(address,uint256)` in [0x10, 0x14). // also cleans the upper bits of `to` mstore(0x00, 0xa9059cbb000000000000000000000000) // Perform the transfer, reverting upon failure. if iszero( and( // The arguments of `and` are evaluated from right to left. or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing. call(gas(), currency, 0, 0x10, 0x44, 0x00, 0x20) ) ) { mstore(0x00, 0xf27f64e4) // `ERC20TransferFailed()`. revert(0x1c, 0x04) } mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten. } } } function balanceOfSelf(Currency currency) internal view returns (uint256) { if (currency.isNative()) { return address(this).balance; } else { return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this)); } } function balanceOf(Currency currency, address owner) internal view returns (uint256) { if (currency.isNative()) { return owner.balance; } else { return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner); } } function isNative(Currency currency) internal pure returns (bool) { return Currency.unwrap(currency) == Currency.unwrap(NATIVE); } function toId(Currency currency) internal pure returns (uint256) { return uint160(Currency.unwrap(currency)); } function fromId(uint256 id) internal pure returns (Currency) { return Currency.wrap(address(uint160(id))); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import {Currency} from "./Currency.sol"; import {IHooks} from "../interfaces/IHooks.sol"; /// @notice Returns the key for identifying a pool struct PoolKey { /// @notice The lower currency of the pool, sorted numerically Currency currency0; /// @notice The higher currency of the pool, sorted numerically Currency currency1; /// @notice The pool swap fee, capped at 1_000_000. If the first bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000 uint24 fee; /// @notice Ticks that involve positions must be a multiple of tick spacing int24 tickSpacing; /// @notice The hooks of the pool IHooks hooks; }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK error InvalidTick(); /// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK error InvalidSqrtPrice(); /// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = 887272; /// @dev The minimum tick spacing value drawn from the range of type int16 that is greater than 0, i.e. min from the range [1, 32767] int24 internal constant MIN_TICK_SPACING = 1; /// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767] int24 internal constant MAX_TICK_SPACING = type(int16).max; /// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_PRICE = 4295128739; /// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342; /// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1` uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE = 1461446703485210103287273052203988822378723970342 - 4295128739 - 1; /// @notice Given a tickSpacing, compute the maximum usable tick function maxUsableTick(int24 tickSpacing) internal pure returns (int24) { unchecked { return (MAX_TICK / tickSpacing) * tickSpacing; } } /// @notice Given a tickSpacing, compute the minimum usable tick function minUsableTick(int24 tickSpacing) internal pure returns (int24) { unchecked { return (MIN_TICK / tickSpacing) * tickSpacing; } } /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0) /// at the given tick function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { unchecked { uint256 absTick; assembly { // mask = 0 if tick >= 0 else -1 (all 1s) let mask := sar(255, tick) // if tick >= 0, |tick| = tick = 0 ^ tick // if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1) // either way, |tick| = mask ^ (tick + mask) absTick := xor(mask, add(mask, tick)) } // Equivalent: if (absTick > MAX_TICK) revert InvalidTick(); assembly ("memory-safe") { if gt(absTick, MAX_TICK) { // store 4-byte selector of "InvalidTick()" at memory [0x1c, 0x20) mstore(0, 0xce8ef7fc) revert(0x1c, 0x04) } } // Equivalent to: // price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; // or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128 uint256 price; assembly { price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1))) } if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128; assembly { // if (tick > 0) price = type(uint256).max / price; if sgt(tick, 0) { price := div(not(0), price) } // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtPrice of the output price is always consistent // `sub(shl(32, 1), 1)` is `type(uint32).max` // `price + type(uint32).max` will not overflow because `price` fits in 192 bits sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1))) } } } /// @notice Calculates the greatest tick value such that getPriceAtTick(tick) <= price /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getPriceAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the price is less than or equal to the input price function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) { unchecked { // Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice(); // second inequality must be < because the price can never reach the price at the max tick assembly ("memory-safe") { // if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true // if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1 if gt(sub(sqrtPriceX96, MIN_SQRT_PRICE), MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) { // store 4-byte selector of "InvalidSqrtPrice()" at memory [0x1c, 0x20) mstore(0, 0x31efafe8) revert(0x1c, 0x04) } } uint256 price = uint256(sqrtPriceX96) << 32; uint256 r = price; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = price >> (msb - 127); else r = price << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.20; import {CustomRevert} from "./libraries/CustomRevert.sol"; /// @title Prevents delegatecall to a contract /// @notice Base contract that provides a modifier for preventing delegatecall to methods in a child contract abstract contract NoDelegateCall { using CustomRevert for bytes4; error DelegateCallNotAllowed(); /// @dev The original address of this contract address private immutable original; constructor() { // Immutables are computed in the init code of the contract, and then inlined into the deployed bytecode. // In other words, this variable won't change when it's checked at runtime. original = address(this); } /// @dev Private method is used instead of inlining into modifier because modifiers are copied into each method, /// and the use of immutable means the address bytes are copied in every place the modifier is used. function checkNotDelegateCall() private view { if (address(this) != original) DelegateCallNotAllowed.selector.revertWith(); } /// @notice Prevents delegatecall into the modified method modifier noDelegateCall() { checkNotDelegateCall(); _; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {PoolKey} from "../types/PoolKey.sol"; import {BalanceDelta} from "../types/BalanceDelta.sol"; import {IPoolManager} from "./IPoolManager.sol"; import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol"; /// @notice The PoolManager contract decides whether to invoke specific hooks by inspecting the leading bits /// of the hooks contract address. For example, a 1 bit in the first bit of the address will /// cause the 'before swap' hook to be invoked. See the Hooks library for the full spec. /// @dev Should only be callable by the v4 PoolManager. interface IHooks { /// @notice The hook called before the state of a pool is initialized /// @param sender The initial msg.sender for the initialize call /// @param key The key for the pool being initialized /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96 /// @param hookData Arbitrary data handed into the PoolManager by the initializer to be be passed on to the hook /// @return bytes4 The function selector for the hook function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, bytes calldata hookData) external returns (bytes4); /// @notice The hook called after the state of a pool is initialized /// @param sender The initial msg.sender for the initialize call /// @param key The key for the pool being initialized /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96 /// @param tick The current tick after the state of a pool is initialized /// @param hookData Arbitrary data handed into the PoolManager by the initializer to be be passed on to the hook /// @return bytes4 The function selector for the hook function afterInitialize( address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick, bytes calldata hookData ) external returns (bytes4); /// @notice The hook called before liquidity is added /// @param sender The initial msg.sender for the add liquidity call /// @param key The key for the pool /// @param params The parameters for adding liquidity /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook /// @return bytes4 The function selector for the hook function beforeAddLiquidity( address sender, PoolKey calldata key, IPoolManager.ModifyLiquidityParams calldata params, bytes calldata hookData ) external returns (bytes4); /// @notice The hook called after liquidity is added /// @param sender The initial msg.sender for the add liquidity call /// @param key The key for the pool /// @param params The parameters for adding liquidity /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook /// @return bytes4 The function selector for the hook /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency function afterAddLiquidity( address sender, PoolKey calldata key, IPoolManager.ModifyLiquidityParams calldata params, BalanceDelta delta, bytes calldata hookData ) external returns (bytes4, BalanceDelta); /// @notice The hook called before liquidity is removed /// @param sender The initial msg.sender for the remove liquidity call /// @param key The key for the pool /// @param params The parameters for removing liquidity /// @param hookData Arbitrary data handed into the PoolManager by the liquidty provider to be be passed on to the hook /// @return bytes4 The function selector for the hook function beforeRemoveLiquidity( address sender, PoolKey calldata key, IPoolManager.ModifyLiquidityParams calldata params, bytes calldata hookData ) external returns (bytes4); /// @notice The hook called after liquidity is removed /// @param sender The initial msg.sender for the remove liquidity call /// @param key The key for the pool /// @param params The parameters for removing liquidity /// @param hookData Arbitrary data handed into the PoolManager by the liquidty provider to be be passed on to the hook /// @return bytes4 The function selector for the hook /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency function afterRemoveLiquidity( address sender, PoolKey calldata key, IPoolManager.ModifyLiquidityParams calldata params, BalanceDelta delta, bytes calldata hookData ) external returns (bytes4, BalanceDelta); /// @notice The hook called before a swap /// @param sender The initial msg.sender for the swap call /// @param key The key for the pool /// @param params The parameters for the swap /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook /// @return bytes4 The function selector for the hook /// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency /// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1) the Pool has a dynamic fee, 2) the value's leading bit is set to 1 (24th bit, 0x800000), 3) the value is less than or equal to the maximum fee (1 million) function beforeSwap( address sender, PoolKey calldata key, IPoolManager.SwapParams calldata params, bytes calldata hookData ) external returns (bytes4, BeforeSwapDelta, uint24); /// @notice The hook called after a swap /// @param sender The initial msg.sender for the swap call /// @param key The key for the pool /// @param params The parameters for the swap /// @param delta The amount owed to the caller (positive) or owed to the pool (negative) /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook /// @return bytes4 The function selector for the hook /// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency function afterSwap( address sender, PoolKey calldata key, IPoolManager.SwapParams calldata params, BalanceDelta delta, bytes calldata hookData ) external returns (bytes4, int128); /// @notice The hook called before donate /// @param sender The initial msg.sender for the donate call /// @param key The key for the pool /// @param amount0 The amount of token0 being donated /// @param amount1 The amount of token1 being donated /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook /// @return bytes4 The function selector for the hook function beforeDonate( address sender, PoolKey calldata key, uint256 amount0, uint256 amount1, bytes calldata hookData ) external returns (bytes4); /// @notice The hook called after donate /// @param sender The initial msg.sender for the donate call /// @param key The key for the pool /// @param amount0 The amount of token0 being donated /// @param amount1 The amount of token1 being donated /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook /// @return bytes4 The function selector for the hook function afterDonate( address sender, PoolKey calldata key, uint256 amount0, uint256 amount1, bytes calldata hookData ) external returns (bytes4); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {Currency} from "../types/Currency.sol"; import {PoolKey} from "../types/PoolKey.sol"; import {Pool} from "../libraries/Pool.sol"; import {IHooks} from "./IHooks.sol"; import {IERC6909Claims} from "./external/IERC6909Claims.sol"; import {IProtocolFees} from "./IProtocolFees.sol"; import {BalanceDelta} from "../types/BalanceDelta.sol"; import {PoolId} from "../types/PoolId.sol"; import {Position} from "../libraries/Position.sol"; import {IExtsload} from "./IExtsload.sol"; import {IExttload} from "./IExttload.sol"; interface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload { /// @notice Thrown when a currency is not netted out after the contract is unlocked error CurrencyNotSettled(); /// @notice Thrown when trying to interact with a non-initialized pool error PoolNotInitialized(); /// @notice Thrown when unlock is called, but the contract is already unlocked error AlreadyUnlocked(); /// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not error ManagerLocked(); /// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow error TickSpacingTooLarge(); /// @notice Pools must have a positive non-zero tickSpacing passed to #initialize error TickSpacingTooSmall(); /// @notice PoolKey must have currencies where address(currency0) < address(currency1) error CurrenciesOutOfOrderOrEqual(); /// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook, /// or on a pool that does not have a dynamic swap fee. error UnauthorizedDynamicLPFeeUpdate(); /// @notice Thrown when trying to swap amount of 0 error SwapAmountCannotBeZero(); ///@notice Thrown when native currency is passed to a non native settlement error NonZeroNativeValue(); /// @notice Emitted when a new pool is initialized /// @param id The abi encoded hash of the pool key struct for the new pool /// @param currency0 The first currency of the pool by address sort order /// @param currency1 The second currency of the pool by address sort order /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks /// @param hooks The hooks contract address for the pool, or address(0) if none event Initialize( PoolId id, Currency indexed currency0, Currency indexed currency1, uint24 fee, int24 tickSpacing, IHooks hooks ); /// @notice Emitted when a liquidity position is modified /// @param id The abi encoded hash of the pool key struct for the pool that was modified /// @param sender The address that modified the pool /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param liquidityDelta The amount of liquidity that was added or removed event ModifyLiquidity( PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta ); /// @notice Emitted for swaps between currency0 and currency1 /// @param id The abi encoded hash of the pool key struct for the pool that was modified /// @param sender The address that initiated the swap call, and that received the callback /// @param amount0 The delta of the currency0 balance of the pool /// @param amount1 The delta of the currency1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of the price of the pool after the swap /// @param fee The swap fee in hundredths of a bip event Swap( PoolId indexed id, address sender, int128 amount0, int128 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick, uint24 fee ); /// @notice Returns the constant representing the maximum tickSpacing for an initialized pool key function MAX_TICK_SPACING() external view returns (int24); /// @notice Returns the constant representing the minimum tickSpacing for an initialized pool key function MIN_TICK_SPACING() external view returns (int24); /// @notice Writes the current ERC20 balance of the specified currency to transient storage /// This is used to checkpoint balances for the manager and derive deltas for the caller. /// @dev This MUST be called before any ERC20 tokens are sent into the contract. function sync(Currency currency) external returns (uint256 balance); /// @notice Initialize the state for a given pool ID function initialize(PoolKey memory key, uint160 sqrtPriceX96, bytes calldata hookData) external returns (int24 tick); /// @notice All operations go through this function /// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)` /// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)` function unlock(bytes calldata data) external returns (bytes memory); struct ModifyLiquidityParams { // the lower and upper tick of the position int24 tickLower; int24 tickUpper; // how to modify the liquidity int256 liquidityDelta; // a value to set if you want unique liquidity positions at the same range bytes32 salt; } /// @notice Modify the liquidity for the given pool /// @dev Poke by calling with a zero liquidityDelta /// @param key The pool to modify liquidity in /// @param params The parameters for modifying the liquidity /// @param hookData Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)` /// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal and fee deltas. /// @return feeDelta The balance delta of the fees generated in the liquidity range. Returned for informational purposes. function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData) external returns (BalanceDelta, BalanceDelta); struct SwapParams { bool zeroForOne; int256 amountSpecified; uint160 sqrtPriceLimitX96; } /// @notice Swap against the given pool /// @param key The pool to swap in /// @param params The parameters for swapping /// @param hookData Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)` /// @return swapDelta The balance delta of the address swapping /// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified. /// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG /// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta. function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData) external returns (BalanceDelta); /// @notice Donate the given currency amounts to the pool with the given pool key function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData) external returns (BalanceDelta); /// @notice Called by the user to net out some value owed to the user /// @dev Can also be used as a mechanism for _free_ flash loans function take(Currency currency, address to, uint256 amount) external; /// @notice Called by the user to move value into ERC6909 balance function mint(address to, uint256 id, uint256 amount) external; /// @notice Called by the user to move value from ERC6909 balance function burn(address from, uint256 id, uint256 amount) external; /// @notice Called by the user to pay what is owed function settle(Currency token) external payable returns (uint256 paid); /// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees. function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; interface IUnlockCallback { /// @notice Called by the pool manager on `msg.sender` when the manager is unlocked /// @param data The data that was passed to the call to unlock /// @return Any data that you want to be returned from the unlock call function unlockCallback(bytes calldata data) external returns (bytes memory); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.19; import {Currency} from "./types/Currency.sol"; import {IProtocolFeeController} from "./interfaces/IProtocolFeeController.sol"; import {IProtocolFees} from "./interfaces/IProtocolFees.sol"; import {PoolKey} from "./types/PoolKey.sol"; import {ProtocolFeeLibrary} from "./libraries/ProtocolFeeLibrary.sol"; import {Owned} from "solmate/auth/Owned.sol"; import {PoolId, PoolIdLibrary} from "./types/PoolId.sol"; import {Pool} from "./libraries/Pool.sol"; import {CustomRevert} from "./libraries/CustomRevert.sol"; abstract contract ProtocolFees is IProtocolFees, Owned { using ProtocolFeeLibrary for uint24; using PoolIdLibrary for PoolKey; using Pool for Pool.State; using CustomRevert for bytes4; mapping(Currency currency => uint256) public protocolFeesAccrued; IProtocolFeeController public protocolFeeController; uint256 private immutable controllerGasLimit; constructor(uint256 _controllerGasLimit) Owned(msg.sender) { controllerGasLimit = _controllerGasLimit; } /// @inheritdoc IProtocolFees function setProtocolFeeController(IProtocolFeeController controller) external onlyOwner { protocolFeeController = controller; emit ProtocolFeeControllerUpdated(address(controller)); } /// @inheritdoc IProtocolFees function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external { if (msg.sender != address(protocolFeeController)) InvalidCaller.selector.revertWith(); if (!newProtocolFee.isValidProtocolFee()) InvalidProtocolFee.selector.revertWith(); PoolId id = key.toId(); _getPool(id).setProtocolFee(newProtocolFee); emit ProtocolFeeUpdated(id, newProtocolFee); } /// @inheritdoc IProtocolFees function collectProtocolFees(address recipient, Currency currency, uint256 amount) external returns (uint256 amountCollected) { if (msg.sender != address(protocolFeeController)) InvalidCaller.selector.revertWith(); amountCollected = (amount == 0) ? protocolFeesAccrued[currency] : amount; protocolFeesAccrued[currency] -= amountCollected; currency.transfer(recipient, amountCollected); } /// @dev abstract internal function to allow the ProtocolFees contract to access pool state /// @dev this is overriden in PoolManager.sol to give access to the _pools mapping function _getPool(PoolId id) internal virtual returns (Pool.State storage); /// @notice Fetch the protocol fees for a given pool, returning false if the call fails or the returned fees are invalid. /// @dev to prevent an invalid protocol fee controller from blocking pools from being initialized /// the success of this function is NOT checked on initialize and if the call fails, the protocol fees are set to 0. /// @dev the success of this function must be checked when called in setProtocolFee function _fetchProtocolFee(PoolKey memory key) internal returns (bool success, uint24 protocolFee) { if (address(protocolFeeController) != address(0)) { // note that EIP-150 mandates that calls requesting more than 63/64ths of remaining gas // will be allotted no more than this amount, so controllerGasLimit must be set with this // in mind. if (gasleft() < controllerGasLimit) ProtocolFeeCannotBeFetched.selector.revertWith(); (bool _success, bytes memory _data) = address(protocolFeeController).call{gas: controllerGasLimit}( abi.encodeCall(IProtocolFeeController.protocolFeeForPool, (key)) ); // Ensure that the return data fits within a word if (!_success || _data.length > 32) return (false, 0); uint256 returnData; assembly ("memory-safe") { returnData := mload(add(_data, 0x20)) } // Ensure return data does not overflow a uint24 and that the underlying fees are within bounds. (success, protocolFee) = (returnData == uint24(returnData)) && uint24(returnData).isValidProtocolFee() ? (true, uint24(returnData)) : (false, 0); } } function _updateProtocolFees(Currency currency, uint256 amount) internal { unchecked { protocolFeesAccrued[currency] += amount; } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import {ERC6909} from "./ERC6909.sol"; /// @notice ERC6909Claims inherits ERC6909 and implements an internal burnFrom function abstract contract ERC6909Claims is ERC6909 { /// @notice Burn `amount` tokens of token type `id` from `from`. /// @dev if sender is not `from` they must be an operator or have sufficient allowance. /// @param from The address to burn tokens from. /// @param id The currency to burn. /// @param amount The amount to burn. function _burnFrom(address from, uint256 id, uint256 amount) internal { address sender = msg.sender; if (from != sender && !isOperator[from][sender]) { uint256 senderAllowance = allowance[from][sender][id]; if (senderAllowance != type(uint256).max) { allowance[from][sender][id] = senderAllowance - amount; } } _burn(from, id, amount); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import {PoolKey} from "./PoolKey.sol"; type PoolId is bytes32; /// @notice Library for computing the ID of a pool library PoolIdLibrary { /// @notice Returns value equal to keccak256(abi.encode(poolKey)) function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) { assembly ("memory-safe") { poolId := keccak256(poolKey, mul(32, 5)) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import {SafeCast} from "../libraries/SafeCast.sol"; /// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0 /// and the lower 128 bits represent the amount1. type BalanceDelta is int256; using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global; using BalanceDeltaLibrary for BalanceDelta global; using SafeCast for int256; function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) { assembly { balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1)) } } function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) { int256 res0; int256 res1; assembly { let a0 := sar(128, a) let a1 := signextend(15, a) let b0 := sar(128, b) let b1 := signextend(15, b) res0 := add(a0, b0) res1 := add(a1, b1) } return toBalanceDelta(res0.toInt128(), res1.toInt128()); } function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) { int256 res0; int256 res1; assembly { let a0 := sar(128, a) let a1 := signextend(15, a) let b0 := sar(128, b) let b1 := signextend(15, b) res0 := sub(a0, b0) res1 := sub(a1, b1) } return toBalanceDelta(res0.toInt128(), res1.toInt128()); } function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) { return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b); } function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) { return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b); } library BalanceDeltaLibrary { BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0); function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) { assembly { _amount0 := sar(128, balanceDelta) } } function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) { assembly { _amount1 := signextend(15, balanceDelta) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import {BalanceDelta} from "./BalanceDelta.sol"; // Return type of the beforeSwap hook. // Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook) type BeforeSwapDelta is int256; // Creates a BeforeSwapDelta from specified and unspecified function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified) pure returns (BeforeSwapDelta beforeSwapDelta) { assembly ("memory-safe") { beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified)) } } library BeforeSwapDeltaLibrary { BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0); /// extracts int128 from the upper 128 bits of the BeforeSwapDelta /// returned by beforeSwap function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) { assembly { deltaSpecified := sar(128, delta) } } /// extracts int128 from the lower 128 bits of the BeforeSwapDelta /// returned by beforeSwap and afterSwap function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) { assembly ("memory-safe") { deltaUnspecified := signextend(15, delta) } } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.20; import {IHooks} from "../interfaces/IHooks.sol"; /// @notice This is a temporary library that allows us to use transient storage (tstore/tload) /// TODO: This library can be deleted when we have the transient keyword support in solidity. library Lock { // The slot holding the unlocked state, transiently. bytes32(uint256(keccak256("Unlocked")) - 1) bytes32 constant IS_UNLOCKED_SLOT = 0xc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab23; function unlock() internal { assembly { // unlock tstore(IS_UNLOCKED_SLOT, true) } } function lock() internal { assembly { tstore(IS_UNLOCKED_SLOT, false) } } function isUnlocked() internal view returns (bool unlocked) { assembly { unlocked := tload(IS_UNLOCKED_SLOT) } } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.20; import {Currency} from "../types/Currency.sol"; /// @title a library to store callers' currency deltas in transient storage /// @dev this library implements the equivalent of a mapping, as transient storage can only be accessed in assembly library CurrencyDelta { /// @notice calculates which storage slot a delta should be stored in for a given caller and currency function _computeSlot(address caller_, Currency currency) internal pure returns (bytes32 hashSlot) { assembly ("memory-safe") { mstore(0, caller_) mstore(32, currency) hashSlot := keccak256(0, 64) } } /// @notice sets a new currency delta for a given caller and currency function setDelta(Currency currency, address caller, int256 delta) internal { bytes32 hashSlot = _computeSlot(caller, currency); assembly { tstore(hashSlot, delta) } } /// @notice gets a new currency delta for a given caller and currency function getDelta(Currency currency, address caller) internal view returns (int256 delta) { bytes32 hashSlot = _computeSlot(caller, currency); assembly { delta := tload(hashSlot) } } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.20; import {IHooks} from "../interfaces/IHooks.sol"; /// @notice This is a temporary library that allows us to use transient storage (tstore/tload) /// for the nonzero delta count. /// TODO: This library can be deleted when we have the transient keyword support in solidity. library NonZeroDeltaCount { // The slot holding the number of nonzero deltas. bytes32(uint256(keccak256("NonzeroDeltaCount")) - 1) bytes32 constant NONZERO_DELTA_COUNT_SLOT = 0x7d4b3164c6e45b97e7d87b7125a44c5828d005af88f9d751cfd78729c5d99a0b; function read() internal view returns (uint256 count) { assembly { count := tload(NONZERO_DELTA_COUNT_SLOT) } } function increment() internal { assembly { let count := tload(NONZERO_DELTA_COUNT_SLOT) count := add(count, 1) tstore(NONZERO_DELTA_COUNT_SLOT, count) } } /// @notice Potential to underflow. /// Current usage ensures this will not happen because we call decrement with known boundaries (only up to the number of times we call increment). function decrement() internal { assembly { let count := tload(NONZERO_DELTA_COUNT_SLOT) count := sub(count, 1) tstore(NONZERO_DELTA_COUNT_SLOT, count) } } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.20; import {Currency} from "../types/Currency.sol"; import {CustomRevert} from "./CustomRevert.sol"; library Reserves { using CustomRevert for bytes4; /// bytes32(uint256(keccak256("ReservesOf")) - 1) bytes32 constant RESERVES_OF_SLOT = 0x1e0745a7db1623981f0b2a5d4232364c00787266eb75ad546f190e6cebe9bd95; /// @notice The transient reserves for pools with no balance is set to the max as a sentinel to track that it has been synced. uint256 public constant ZERO_BALANCE = type(uint256).max; /// @notice Thrown when someone has not called sync before calling settle for the first time. error ReservesMustBeSynced(); function setReserves(Currency currency, uint256 value) internal { if (value == 0) value = ZERO_BALANCE; bytes32 key = _getKey(currency); assembly { tstore(key, value) } } function getReserves(Currency currency) internal view returns (uint256 value) { bytes32 key = _getKey(currency); assembly { value := tload(key) } if (value == 0) ReservesMustBeSynced.selector.revertWith(); if (value == ZERO_BALANCE) value = 0; } function _getKey(Currency currency) private pure returns (bytes32 key) { assembly ("memory-safe") { mstore(0, RESERVES_OF_SLOT) mstore(32, currency) key := keccak256(0, 64) } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import {IExtsload} from "./interfaces/IExtsload.sol"; /// @notice Enables public storage access for efficient state retrieval by external contracts. /// https://eips.ethereum.org/EIPS/eip-2330#rationale abstract contract Extsload is IExtsload { /// @inheritdoc IExtsload function extsload(bytes32 slot) external view returns (bytes32) { assembly ("memory-safe") { mstore(0, sload(slot)) return(0, 0x20) } } /// @inheritdoc IExtsload function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes memory) { assembly ("memory-safe") { // The abi offset of dynamic array in the returndata is 32. mstore(0, 0x20) // A left bit-shift of 5 is equivalent to multiplying by 32 but costs less gas. mstore(0x20, shl(5, nSlots)) let end := add(0x40, shl(5, nSlots)) for { let memptr := 0x40 } 1 {} { mstore(memptr, sload(startSlot)) memptr := add(memptr, 0x20) startSlot := add(startSlot, 1) if iszero(lt(memptr, end)) { break } } // The end offset is also the length of the returndata. return(0, end) } } /// @inheritdoc IExtsload function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory) { // since the function is external and enters a new call context and exits right // after execution, Solidity's memory management convention can be disregarded // and a direct slice of memory can be returned assembly ("memory-safe") { // Copy the abi offset of dynamic array and the length of the array to memory. calldatacopy(0, 0x04, 0x40) // A left bit-shift of 5 is equivalent to multiplying by 32 but costs less gas. let end := add(0x40, shl(5, slots.length)) let calldataptr := slots.offset // Return values will start at 64 while calldata offset is 68. for { let memptr := 0x40 } 1 {} { mstore(memptr, sload(calldataload(calldataptr))) memptr := add(memptr, 0x20) calldataptr := add(calldataptr, 0x20) if iszero(lt(memptr, end)) { break } } // The end offset is also the length of the returndata. return(0, end) } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.24; import {IExttload} from "./interfaces/IExttload.sol"; /// @notice Enables public transient storage access for efficient state retrieval by external contracts. /// https://eips.ethereum.org/EIPS/eip-2330#rationale abstract contract Exttload is IExttload { /// @inheritdoc IExttload function exttload(bytes32 slot) external view returns (bytes32) { assembly ("memory-safe") { mstore(0, tload(slot)) return(0, 0x20) } } /// @inheritdoc IExttload function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory) { // since the function is external and enters a new call context and exits right // after execution, Solidity's memory management convention can be disregarded // and a direct slice of memory can be returned assembly ("memory-safe") { // Copy the abi offset of dynamic array and the length of the array to memory. calldatacopy(0, 0x04, 0x40) // A left bit-shift of 5 is equivalent to multiplying by 32 but costs less gas. let end := add(0x40, shl(5, slots.length)) let calldataptr := slots.offset // Return values will start at 64 while calldata offset is 68. for { let memptr := 0x40 } 1 {} { mstore(memptr, tload(calldataload(calldataptr))) memptr := add(memptr, 0x20) calldataptr := add(calldataptr, 0x20) if iszero(lt(memptr, end)) { break } } // The end offset is also the length of the returndata. return(0, end) } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.4; /// @title Library for reverting with custom errors efficiently /// @notice Contains functions for reverting with custom errors with different argument types efficiently /// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with /// `CustomError.selector.revertWith()` /// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately library CustomRevert { /// @dev Reverts with the selector of a custom error in the scratch space function revertWith(bytes4 selector) internal pure { assembly ("memory-safe") { mstore(0, selector) revert(0, 0x04) } } /// @dev Reverts with a custom error with an address argument in the scratch space function revertWith(bytes4 selector, address addr) internal pure { assembly ("memory-safe") { mstore(0, selector) mstore(0x04, addr) revert(0, 0x24) } } /// @dev Reverts with a custom error with an int24 argument in the scratch space function revertWith(bytes4 selector, int24 value) internal pure { assembly ("memory-safe") { mstore(0, selector) mstore(0x04, value) revert(0, 0x24) } } /// @dev Reverts with a custom error with a uint160 argument in the scratch space function revertWith(bytes4 selector, uint160 value) internal pure { assembly ("memory-safe") { mstore(0, selector) mstore(0x04, value) revert(0, 0x24) } } /// @dev Reverts with a custom error with two int24 arguments function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure { assembly ("memory-safe") { mstore(0, selector) mstore(0x04, value1) mstore(0x24, value2) revert(0, 0x44) } } /// @dev Reverts with a custom error with two uint160 arguments function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure { assembly ("memory-safe") { mstore(0, selector) mstore(0x04, value1) mstore(0x24, value2) revert(0, 0x44) } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @notice Parses bytes returned from hooks and the byte selector used to check return selectors from hooks. /// @dev parseSelector also is used to parse the expected selector /// For parsing hook returns, note that all hooks return either bytes4 or (bytes4, 32-byte-delta) or (bytes4, 32-byte-delta, uint24). library ParseBytes { function parseSelector(bytes memory result) internal pure returns (bytes4 selector) { // equivalent: (selector,) = abi.decode(result, (bytes4, int256)); assembly ("memory-safe") { selector := mload(add(result, 0x20)) } } function parseFee(bytes memory result) internal pure returns (uint24 lpFee) { // equivalent: (,, lpFee) = abi.decode(result, (bytes4, int256, uint24)); assembly ("memory-safe") { lpFee := mload(add(result, 0x60)) } } function parseReturnDelta(bytes memory result) internal pure returns (int256 hookReturn) { // equivalent: (, hookReturnDelta) = abi.decode(result, (bytes4, int256)); assembly ("memory-safe") { hookReturn := mload(add(result, 0x40)) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import {BitMath} from "./BitMath.sol"; /// @title Packed tick initialized state library /// @notice Stores a packed mapping of tick index to its initialized state /// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word. library TickBitmap { /// @notice Thrown when the tick is not enumerated by the tick spacing /// @param tick the invalid tick /// @param tickSpacing The tick spacing of the pool error TickMisaligned(int24 tick, int24 tickSpacing); /// @dev round towards negative infinity function compress(int24 tick, int24 tickSpacing) internal pure returns (int24 compressed) { // compressed = tick / tickSpacing; // if (tick < 0 && tick % tickSpacing != 0) compressed--; assembly { compressed := sub( sdiv(tick, tickSpacing), // if (tick < 0 && tick % tickSpacing != 0) then tick % tickSpacing < 0, vice versa slt(smod(tick, tickSpacing), 0) ) } } /// @notice Computes the position in the mapping where the initialized bit for a tick lives /// @param tick The tick for which to compute the position /// @return wordPos The key in the mapping containing the word in which the bit is stored /// @return bitPos The bit position in the word where the flag is stored function position(int24 tick) internal pure returns (int16 wordPos, uint8 bitPos) { assembly { // signed arithmetic shift right wordPos := sar(8, tick) bitPos := and(tick, 0xff) } } /// @notice Flips the initialized state for a given tick from false to true, or vice versa /// @param self The mapping in which to flip the tick /// @param tick The tick to flip /// @param tickSpacing The spacing between usable ticks function flipTick(mapping(int16 => uint256) storage self, int24 tick, int24 tickSpacing) internal { /** * Equivalent to the following Solidity: * if (tick % tickSpacing != 0) revert TickMisaligned(tick, tickSpacing); * (int16 wordPos, uint8 bitPos) = position(tick / tickSpacing); * uint256 mask = 1 << bitPos; * self[wordPos] ^= mask; */ assembly ("memory-safe") { // ensure that the tick is spaced if smod(tick, tickSpacing) { mstore(0, 0xd4d8f3e6) // selector for TickMisaligned(int24,int24) mstore(0x20, tick) mstore(0x40, tickSpacing) revert(0x1c, 0x44) } tick := sdiv(tick, tickSpacing) // calculate the storage slot corresponding to the tick // wordPos = tick >> 8 mstore(0, sar(8, tick)) mstore(0x20, self.slot) // the slot of self[wordPos] is keccak256(abi.encode(wordPos, self.slot)) let slot := keccak256(0, 0x40) // mask = 1 << bitPos = 1 << (tick % 256) // self[wordPos] ^= mask sstore(slot, xor(sload(slot), shl(and(tick, 0xff), 1))) } } /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either /// to the left (less than or equal to) or right (greater than) of the given tick /// @param self The mapping in which to compute the next initialized tick /// @param tick The starting tick /// @param tickSpacing The spacing between usable ticks /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick) /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks function nextInitializedTickWithinOneWord( mapping(int16 => uint256) storage self, int24 tick, int24 tickSpacing, bool lte ) internal view returns (int24 next, bool initialized) { unchecked { int24 compressed = compress(tick, tickSpacing); if (lte) { (int16 wordPos, uint8 bitPos) = position(compressed); // all the 1s at or to the right of the current bitPos uint256 mask = (1 << bitPos) - 1 + (1 << bitPos); uint256 masked = self[wordPos] & mask; // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word initialized = masked != 0; // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick next = initialized ? (compressed - int24(uint24(bitPos - BitMath.mostSignificantBit(masked)))) * tickSpacing : (compressed - int24(uint24(bitPos))) * tickSpacing; } else { // start from the word of the next tick, since the current tick state doesn't matter (int16 wordPos, uint8 bitPos) = position(++compressed); // all the 1s at or to the left of the bitPos uint256 mask = ~((1 << bitPos) - 1); uint256 masked = self[wordPos] & mask; // if there are no initialized ticks to the left of the current tick, return leftmost in the word initialized = masked != 0; // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick next = initialized ? (compressed + int24(uint24(BitMath.leastSignificantBit(masked) - bitPos))) * tickSpacing : (compressed + int24(uint24(type(uint8).max - bitPos))) * tickSpacing; } } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0 = a * b; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { assembly { result := div(prod0, denominator) } return result; } /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = (0 - denominator) & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the preconditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) { unchecked { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) != 0) { require(++result > 0); } } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @title FixedPoint128 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint128 { uint256 internal constant Q128 = 0x100000000000000000000000000000000; }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; import {SafeCast} from "./SafeCast.sol"; import {FullMath} from "./FullMath.sol"; import {UnsafeMath} from "./UnsafeMath.sol"; import {FixedPoint96} from "./FixedPoint96.sol"; /// @title Functions based on Q64.96 sqrt price and liquidity /// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas library SqrtPriceMath { using SafeCast for uint256; error InvalidPriceOrLiquidity(); error InvalidPrice(); error NotEnoughLiquidity(); error PriceOverflow(); /// @notice Gets the next sqrt price given a delta of currency0 /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the /// price less in order to not send too much output. /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96), /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount). /// @param sqrtPX96 The starting price, i.e. before accounting for the currency0 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of currency0 to add or remove from virtual reserves /// @param add Whether to add or remove the amount of currency0 /// @return The price after adding or removing amount, depending on add function getNextSqrtPriceFromAmount0RoundingUp(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add) internal pure returns (uint160) { // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price if (amount == 0) return sqrtPX96; uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; if (add) { unchecked { uint256 product = amount * sqrtPX96; if (product / amount == sqrtPX96) { uint256 denominator = numerator1 + product; if (denominator >= numerator1) { // always fits in 160 bits return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator)); } } } // denominator is checked for overflow return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96) + amount)); } else { unchecked { uint256 product = amount * sqrtPX96; // if the product overflows, we know the denominator underflows // in addition, we must check that the denominator does not underflow // equivalent: if (product / amount != sqrtPX96 || numerator1 <= product) revert PriceOverflow(); assembly ("memory-safe") { if iszero(and(eq(div(product, amount), sqrtPX96), gt(numerator1, product))) { mstore(0, 0xf5c787f1) // selector for PriceOverflow() revert(0x1c, 0x04) } } uint256 denominator = numerator1 - product; return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160(); } } } /// @notice Gets the next sqrt price given a delta of currency1 /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the /// price less in order to not send too much output. /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity /// @param sqrtPX96 The starting price, i.e., before accounting for the currency1 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of currency1 to add, or remove, from virtual reserves /// @param add Whether to add, or remove, the amount of currency1 /// @return The price after adding or removing `amount` function getNextSqrtPriceFromAmount1RoundingDown(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add) internal pure returns (uint160) { // if we're adding (subtracting), rounding down requires rounding the quotient down (up) // in both cases, avoid a mulDiv for most inputs if (add) { uint256 quotient = ( amount <= type(uint160).max ? (amount << FixedPoint96.RESOLUTION) / liquidity : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity) ); return (uint256(sqrtPX96) + quotient).toUint160(); } else { uint256 quotient = ( amount <= type(uint160).max ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity) : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity) ); // equivalent: if (sqrtPX96 <= quotient) revert NotEnoughLiquidity(); assembly ("memory-safe") { if iszero(gt(sqrtPX96, quotient)) { mstore(0, 0x4323a555) // selector for NotEnoughLiquidity() revert(0x1c, 0x04) } } // always fits 160 bits unchecked { return uint160(sqrtPX96 - quotient); } } } /// @notice Gets the next sqrt price given an input amount of currency0 or currency1 /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount /// @param liquidity The amount of usable liquidity /// @param amountIn How much of currency0, or currency1, is being swapped in /// @param zeroForOne Whether the amount in is currency0 or currency1 /// @return sqrtQX96 The price after adding the input amount to currency0 or currency1 function getNextSqrtPriceFromInput(uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne) internal pure returns (uint160 sqrtQX96) { // equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity(); assembly ("memory-safe") { if or(iszero(sqrtPX96), iszero(liquidity)) { mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity() revert(0x1c, 0x04) } } // round to make sure that we don't pass the target price return zeroForOne ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true) : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true); } /// @notice Gets the next sqrt price given an output amount of currency0 or currency1 /// @dev Throws if price or liquidity are 0 or the next price is out of bounds /// @param sqrtPX96 The starting price before accounting for the output amount /// @param liquidity The amount of usable liquidity /// @param amountOut How much of currency0, or currency1, is being swapped out /// @param zeroForOne Whether the amount out is currency1 or currency0 /// @return sqrtQX96 The price after removing the output amount of currency0 or currency1 function getNextSqrtPriceFromOutput(uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne) internal pure returns (uint160 sqrtQX96) { // equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity(); assembly ("memory-safe") { if or(iszero(sqrtPX96), iszero(liquidity)) { mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity() revert(0x1c, 0x04) } } // round to make sure that we pass the target price return zeroForOne ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false); } /// @notice Gets the amount0 delta between two prices /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper), /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower)) /// @param sqrtPriceAX96 A sqrt price /// @param sqrtPriceBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up or down /// @return amount0 Amount of currency0 required to cover a position of size liquidity between the two passed prices function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp) internal pure returns (uint256 amount0) { unchecked { if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96); // equivalent: if (sqrtPriceAX96 == 0) revert InvalidPrice(); assembly ("memory-safe") { if iszero(sqrtPriceAX96) { mstore(0, 0x00bfc921) // selector for InvalidPrice() revert(0x1c, 0x04) } } uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; uint256 numerator2 = sqrtPriceBX96 - sqrtPriceAX96; return roundUp ? UnsafeMath.divRoundingUp(FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtPriceBX96), sqrtPriceAX96) : FullMath.mulDiv(numerator1, numerator2, sqrtPriceBX96) / sqrtPriceAX96; } } /// @notice Equivalent to: `a >= b ? a - b : b - a` function absDiff(uint160 a, uint160 b) internal pure returns (uint256 res) { assembly { let diff := sub(a, b) // mask = 0 if a >= b else -1 (all 1s) let mask := sar(255, diff) // if a >= b, res = a - b = 0 ^ (a - b) // if a < b, res = b - a = ~~(b - a) = ~(-(b - a) - 1) = ~(a - b - 1) = (-1) ^ (a - b - 1) // either way, res = mask ^ (a - b + mask) res := xor(mask, add(mask, diff)) } } /// @notice Gets the amount1 delta between two prices /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower)) /// @param sqrtPriceAX96 A sqrt price /// @param sqrtPriceBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up, or down /// @return amount1 Amount of currency1 required to cover a position of size liquidity between the two passed prices function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp) internal pure returns (uint256 amount1) { uint256 numerator = absDiff(sqrtPriceAX96, sqrtPriceBX96); uint256 denominator = FixedPoint96.Q96; uint256 _liquidity; assembly { // avoid implicit upcasting _liquidity := liquidity } /** * Equivalent to: * amount1 = roundUp * ? FullMath.mulDivRoundingUp(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96) * : FullMath.mulDiv(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96); * Cannot overflow because `type(uint128).max * type(uint160).max >> 96 < (1 << 192)`. */ amount1 = FullMath.mulDiv(_liquidity, numerator, denominator); assembly { amount1 := add(amount1, and(gt(mulmod(_liquidity, numerator, denominator), 0), roundUp)) } } /// @notice Helper that gets signed currency0 delta /// @param sqrtPriceAX96 A sqrt price /// @param sqrtPriceBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount0 delta /// @return amount0 Amount of currency0 corresponding to the passed liquidityDelta between the two prices function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity) internal pure returns (int256 amount0) { unchecked { return liquidity < 0 ? getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256() : -getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256(); } } /// @notice Helper that gets signed currency1 delta /// @param sqrtPriceAX96 A sqrt price /// @param sqrtPriceBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount1 delta /// @return amount1 Amount of currency1 corresponding to the passed liquidityDelta between the two prices function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity) internal pure returns (int256 amount1) { unchecked { return liquidity < 0 ? getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256() : -getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256(); } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; import {FullMath} from "./FullMath.sol"; import {SqrtPriceMath} from "./SqrtPriceMath.sol"; /// @title Computes the result of a swap within ticks /// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick. library SwapMath { uint256 internal constant MAX_FEE_PIPS = 1e6; /// @notice Computes the sqrt price target for the next swap step /// @param zeroForOne The direction of the swap, true for currency0 to currency1, false for currency1 to currency0 /// @param sqrtPriceNextX96 The Q64.96 sqrt price for the next initialized tick /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value /// after the swap. If one for zero, the price cannot be greater than this value after the swap /// @return sqrtPriceTargetX96 The price target for the next swap step function getSqrtPriceTarget(bool zeroForOne, uint160 sqrtPriceNextX96, uint160 sqrtPriceLimitX96) internal pure returns (uint160 sqrtPriceTargetX96) { assembly { // a flag to toggle between sqrtPriceNextX96 and sqrtPriceLimitX96 // when zeroForOne == true, nextOrLimit reduces to sqrtPriceNextX96 >= sqrtPriceLimitX96 // sqrtPriceTargetX96 = max(sqrtPriceNextX96, sqrtPriceLimitX96) // when zeroForOne == false, nextOrLimit reduces to sqrtPriceNextX96 < sqrtPriceLimitX96 // sqrtPriceTargetX96 = min(sqrtPriceNextX96, sqrtPriceLimitX96) let nextOrLimit := xor(lt(sqrtPriceNextX96, sqrtPriceLimitX96), zeroForOne) let symDiff := xor(sqrtPriceNextX96, sqrtPriceLimitX96) sqrtPriceTargetX96 := xor(sqrtPriceLimitX96, mul(symDiff, nextOrLimit)) } } /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap /// @dev If the swap's amountSpecified is negative, the combined fee and input amount will never exceed the absolute value of the remaining amount. /// @param sqrtPriceCurrentX96 The current sqrt price of the pool /// @param sqrtPriceTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred /// @param liquidity The usable liquidity /// @param amountRemaining How much input or output amount is remaining to be swapped in/out /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip /// @return sqrtPriceNextX96 The price after swapping the amount in/out, not to exceed the price target /// @return amountIn The amount to be swapped in, of either currency0 or currency1, based on the direction of the swap /// @return amountOut The amount to be received, of either currency0 or currency1, based on the direction of the swap /// @return feeAmount The amount of input that will be taken as a fee function computeSwapStep( uint160 sqrtPriceCurrentX96, uint160 sqrtPriceTargetX96, uint128 liquidity, int256 amountRemaining, uint24 feePips ) internal pure returns (uint160 sqrtPriceNextX96, uint256 amountIn, uint256 amountOut, uint256 feeAmount) { unchecked { uint256 _feePips = feePips; // upcast once and cache bool zeroForOne = sqrtPriceCurrentX96 >= sqrtPriceTargetX96; bool exactIn = amountRemaining < 0; if (exactIn) { uint256 amountRemainingLessFee = FullMath.mulDiv(uint256(-amountRemaining), MAX_FEE_PIPS - _feePips, MAX_FEE_PIPS); amountIn = zeroForOne ? SqrtPriceMath.getAmount0Delta(sqrtPriceTargetX96, sqrtPriceCurrentX96, liquidity, true) : SqrtPriceMath.getAmount1Delta(sqrtPriceCurrentX96, sqrtPriceTargetX96, liquidity, true); if (amountRemainingLessFee >= amountIn) { // `amountIn` is capped by the target price sqrtPriceNextX96 = sqrtPriceTargetX96; feeAmount = _feePips == MAX_FEE_PIPS ? amountIn : FullMath.mulDivRoundingUp(amountIn, _feePips, MAX_FEE_PIPS - _feePips); } else { sqrtPriceNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput( sqrtPriceCurrentX96, liquidity, amountRemainingLessFee, zeroForOne ); amountIn = zeroForOne ? SqrtPriceMath.getAmount0Delta(sqrtPriceNextX96, sqrtPriceCurrentX96, liquidity, true) : SqrtPriceMath.getAmount1Delta(sqrtPriceCurrentX96, sqrtPriceNextX96, liquidity, true); // we didn't reach the target, so take the remainder of the maximum input as fee feeAmount = uint256(-amountRemaining) - amountIn; } amountOut = zeroForOne ? SqrtPriceMath.getAmount1Delta(sqrtPriceNextX96, sqrtPriceCurrentX96, liquidity, false) : SqrtPriceMath.getAmount0Delta(sqrtPriceCurrentX96, sqrtPriceNextX96, liquidity, false); } else { amountOut = zeroForOne ? SqrtPriceMath.getAmount1Delta(sqrtPriceTargetX96, sqrtPriceCurrentX96, liquidity, false) : SqrtPriceMath.getAmount0Delta(sqrtPriceCurrentX96, sqrtPriceTargetX96, liquidity, false); if (uint256(amountRemaining) >= amountOut) { // `amountOut` is capped by the target price sqrtPriceNextX96 = sqrtPriceTargetX96; } else { // cap the output amount to not exceed the remaining output amount amountOut = uint256(amountRemaining); sqrtPriceNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(sqrtPriceCurrentX96, liquidity, amountOut, zeroForOne); } amountIn = zeroForOne ? SqrtPriceMath.getAmount0Delta(sqrtPriceNextX96, sqrtPriceCurrentX96, liquidity, true) : SqrtPriceMath.getAmount1Delta(sqrtPriceCurrentX96, sqrtPriceNextX96, liquidity, true); // `feePips` cannot be `MAX_FEE_PIPS` for exact out feeAmount = FullMath.mulDivRoundingUp(amountIn, _feePips, MAX_FEE_PIPS - _feePips); } } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; /** * @dev Slot0 is a packed version of solidity structure. * Using the packaged version saves gas by not storing the structure fields in memory slots. * * Layout: * 24 bits empty | 24 bits lpFee | 24 bits protocolFee | 24 bits tick | 160 bits sqrtPriceX96 * * Fields in the direction from the least significant bit: * * The current price * uint160 sqrtPriceX96; * * The current tick * int24 tick; * * Protocol fee, expressed in hundredths of a bip, upper 12 bits are for 1->0, and the lower 12 are for 0->1 * the maximum is 1000 - meaning the maximum protocol fee is 0.1% * the protocolFee is taken from the input first, then the lpFee is taken from the remaining input * uint24 protocolFee; * * Used for the lp fee, either static at initialize or dynamic via hook * uint24 lpFee; */ type Slot0 is bytes32; using Slot0Library for Slot0 global; library Slot0Library { uint160 internal constant MASK_160_BITS = 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; uint24 internal constant MASK_24_BITS = 0xFFFFFF; uint8 internal constant TICK_OFFSET = 160; uint8 internal constant PROTOCOL_FEE_OFFSET = 184; uint8 internal constant LP_FEE_OFFSET = 208; // #### GETTERS #### function sqrtPriceX96(Slot0 _packed) internal pure returns (uint160 _sqrtPriceX96) { assembly ("memory-safe") { _sqrtPriceX96 := and(MASK_160_BITS, _packed) } } function tick(Slot0 _packed) internal pure returns (int24 _tick) { assembly ("memory-safe") { _tick := signextend(2, shr(TICK_OFFSET, _packed)) } } function protocolFee(Slot0 _packed) internal pure returns (uint24 _protocolFee) { assembly ("memory-safe") { _protocolFee := and(MASK_24_BITS, shr(PROTOCOL_FEE_OFFSET, _packed)) } } function lpFee(Slot0 _packed) internal pure returns (uint24 _lpFee) { assembly ("memory-safe") { _lpFee := and(MASK_24_BITS, shr(LP_FEE_OFFSET, _packed)) } } // #### SETTERS #### function setSqrtPriceX96(Slot0 _packed, uint160 _sqrtPriceX96) internal pure returns (Slot0 _result) { assembly ("memory-safe") { _result := or(and(not(MASK_160_BITS), _packed), and(MASK_160_BITS, _sqrtPriceX96)) } } function setTick(Slot0 _packed, int24 _tick) internal pure returns (Slot0 _result) { assembly ("memory-safe") { _result := or(and(not(shl(TICK_OFFSET, MASK_24_BITS)), _packed), shl(TICK_OFFSET, and(MASK_24_BITS, _tick))) } } function setProtocolFee(Slot0 _packed, uint24 _protocolFee) internal pure returns (Slot0 _result) { assembly ("memory-safe") { _result := or( and(not(shl(PROTOCOL_FEE_OFFSET, MASK_24_BITS)), _packed), shl(PROTOCOL_FEE_OFFSET, and(MASK_24_BITS, _protocolFee)) ) } } function setLpFee(Slot0 _packed, uint24 _lpFee) internal pure returns (Slot0 _result) { assembly ("memory-safe") { _result := or(and(not(shl(LP_FEE_OFFSET, MASK_24_BITS)), _packed), shl(LP_FEE_OFFSET, and(MASK_24_BITS, _lpFee))) } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; library ProtocolFeeLibrary { // Max protocol fee is 0.1% (1000 pips) uint16 public constant MAX_PROTOCOL_FEE = 1000; // Thresholds used for optimized bounds checks on protocol fees uint24 internal constant FEE_0_THRESHOLD = 1001; uint24 internal constant FEE_1_THRESHOLD = 1001 << 12; // the protocol fee is represented in hundredths of a bip uint256 internal constant PIPS_DENOMINATOR = 1_000_000; function getZeroForOneFee(uint24 self) internal pure returns (uint16) { return uint16(self & 0xfff); } function getOneForZeroFee(uint24 self) internal pure returns (uint16) { return uint16(self >> 12); } function isValidProtocolFee(uint24 self) internal pure returns (bool valid) { // Equivalent to: getZeroForOneFee(self) <= MAX_PROTOCOL_FEE && getOneForZeroFee(self) <= MAX_PROTOCOL_FEE assembly { let isZeroForOneFeeOk := lt(and(self, 0xfff), FEE_0_THRESHOLD) let isOneForZeroFeeOk := lt(self, FEE_1_THRESHOLD) valid := and(isZeroForOneFeeOk, isOneForZeroFeeOk) } } // The protocol fee is taken from the input amount first and then the LP fee is taken from the remaining // The swap fee is capped at 100% // Equivalent to protocolFee + lpFee(1_000_000 - protocolFee) / 1_000_000 function calculateSwapFee(uint24 self, uint24 lpFee) internal pure returns (uint24 swapFee) { // protocolFee + lpFee - (protocolFee * lpFee / 1_000_000). Div rounds up to favor LPs over the protocol. assembly { let numerator := mul(self, lpFee) let divRoundingUp := add(div(numerator, PIPS_DENOMINATOR), gt(mod(numerator, PIPS_DENOMINATOR), 0)) swapFee := sub(add(self, lpFee), divRoundingUp) } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @title Math library for liquidity library LiquidityMath { /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows /// @param x The liquidity before change /// @param y The delta by which liquidity should be changed /// @return z The liquidity delta function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) { assembly ("memory-safe") { z := add(x, y) if shr(128, z) { // revert SafeCastOverflow() mstore(0, 0x93dafdf1) revert(0x1c, 0x04) } } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @title Minimal ERC20 interface for Uniswap /// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3 interface IERC20Minimal { /// @notice Returns the balance of a token /// @param account The account for which to look up the number of tokens it has, i.e. its balance /// @return The number of tokens held by the account function balanceOf(address account) external view returns (uint256); /// @notice Transfers the amount of token from the `msg.sender` to the recipient /// @param recipient The account that will receive the amount transferred /// @param amount The number of tokens to send from the sender to the recipient /// @return Returns true for a successful transfer, false for an unsuccessful transfer function transfer(address recipient, uint256 amount) external returns (bool); /// @notice Returns the current allowance given to a spender by an owner /// @param owner The account of the token owner /// @param spender The account of the token spender /// @return The current allowance granted by `owner` to `spender` function allowance(address owner, address spender) external view returns (uint256); /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount` /// @param spender The account which will be allowed to spend a given amount of the owners tokens /// @param amount The amount of tokens allowed to be used by `spender` /// @return Returns true for a successful approval, false for unsuccessful function approve(address spender, uint256 amount) external returns (bool); /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender` /// @param sender The account from which the transfer will be initiated /// @param recipient The recipient of the transfer /// @param amount The amount of the transfer /// @return Returns true for a successful transfer, false for unsuccessful function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`. /// @param from The account from which the tokens were sent, i.e. the balance decreased /// @param to The account to which the tokens were sent, i.e. the balance increased /// @param value The amount of tokens that were transferred event Transfer(address indexed from, address indexed to, uint256 value); /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes. /// @param owner The account that approved spending of its tokens /// @param spender The account for which the spending allowance was modified /// @param value The new allowance from the owner to the spender event Approval(address indexed owner, address indexed spender, uint256 value); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface IERC6909Claims { /// @notice Owner balance of an id. /// @param owner The address of the owner. /// @param id The id of the token. /// @return amount The balance of the token. function balanceOf(address owner, uint256 id) external view returns (uint256 amount); /// @notice Spender allowance of an id. /// @param owner The address of the owner. /// @param spender The address of the spender. /// @param id The id of the token. /// @return amount The allowance of the token. function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount); /// @notice Checks if a spender is approved by an owner as an operator /// @param owner The address of the owner. /// @param spender The address of the spender. /// @return approved The approval status. function isOperator(address owner, address spender) external view returns (bool approved); /// @notice Transfers an amount of an id from the caller to a receiver. /// @param receiver The address of the receiver. /// @param id The id of the token. /// @param amount The amount of the token. function transfer(address receiver, uint256 id, uint256 amount) external returns (bool); /// @notice Transfers an amount of an id from a sender to a receiver. /// @param sender The address of the sender. /// @param receiver The address of the receiver. /// @param id The id of the token. /// @param amount The amount of the token. function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool); /// @notice Approves an amount of an id to a spender. /// @param spender The address of the spender. /// @param id The id of the token. /// @param amount The amount of the token. function approve(address spender, uint256 id, uint256 amount) external returns (bool); /// @notice Sets or removes a spender as an operator for the caller. /// @param spender The address of the spender. /// @param approved The approval status. function setOperator(address spender, bool approved) external returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import {Currency} from "../types/Currency.sol"; import {IProtocolFeeController} from "../interfaces/IProtocolFeeController.sol"; import {PoolId} from "../types/PoolId.sol"; import {PoolKey} from "../types/PoolKey.sol"; interface IProtocolFees { /// @notice Thrown when not enough gas is provided to look up the protocol fee error ProtocolFeeCannotBeFetched(); /// @notice Thrown when protocol fee is set too high error InvalidProtocolFee(); /// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller. error InvalidCaller(); event ProtocolFeeControllerUpdated(address protocolFeeController); event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee); /// @notice Given a currency address, returns the protocol fees accrued in that currency function protocolFeesAccrued(Currency) external view returns (uint256); /// @notice Sets the protocol fee for the given pool function setProtocolFee(PoolKey memory key, uint24) external; /// @notice Sets the protocol fee controller function setProtocolFeeController(IProtocolFeeController) external; /// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected function collectProtocolFees(address, Currency, uint256) external returns (uint256); function protocolFeeController() external view returns (IProtocolFeeController); }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface IExtsload { /// @notice Called by external contracts to access granular pool state /// @param slot Key of slot to sload /// @return value The value of the slot as bytes32 function extsload(bytes32 slot) external view returns (bytes32 value); /// @notice Called by external contracts to access granular pool state /// @param slot Key of slot to start sloading from /// @param nSlots Number of slots to load into return value /// @return value The value of the sload-ed slots concatenated as dynamic bytes function extsload(bytes32 slot, uint256 nSlots) external view returns (bytes memory value); /// @notice Called by external contracts to access sparse pool state /// @param slots List of slots to SLOAD from. /// @return values List of loaded values. function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.24; interface IExttload { /// @notice Called by external contracts to access transient storage of the contract /// @param slot Key of slot to tload /// @return value The value of the slot as bytes32 function exttload(bytes32 slot) external view returns (bytes32 value); /// @notice Called by external contracts to access sparse transient pool state /// @param slots List of slots to tload /// @return values List of loaded values function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import {PoolKey} from "../types/PoolKey.sol"; interface IProtocolFeeController { /// @notice Returns the protocol fees for a pool given the conditions of this contract /// @param poolKey The pool key to identify the pool. The controller may want to use attributes on the pool /// to determine the protocol fee, hence the entire key is needed. function protocolFeeForPool(PoolKey memory poolKey) external view returns (uint24); }
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Simple single owner authorization mixin. /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Owned.sol) abstract contract Owned { /*////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event OwnershipTransferred(address indexed user, address indexed newOwner); /*////////////////////////////////////////////////////////////// OWNERSHIP STORAGE //////////////////////////////////////////////////////////////*/ address public owner; modifier onlyOwner() virtual { require(msg.sender == owner, "UNAUTHORIZED"); _; } /*////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor(address _owner) { owner = _owner; emit OwnershipTransferred(address(0), _owner); } /*////////////////////////////////////////////////////////////// OWNERSHIP LOGIC //////////////////////////////////////////////////////////////*/ function transferOwnership(address newOwner) public virtual onlyOwner { owner = newOwner; emit OwnershipTransferred(msg.sender, newOwner); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import {IERC6909Claims} from "./interfaces/external/IERC6909Claims.sol"; /// @notice Minimalist and gas efficient standard ERC6909 implementation. /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC6909.sol) /// @dev Copied from the commit at 4b47a19038b798b4a33d9749d25e570443520647 /// @dev This contract has been modified from the implementation at the above link. abstract contract ERC6909 is IERC6909Claims { /*////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event OperatorSet(address indexed owner, address indexed operator, bool approved); event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount); event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount); /*////////////////////////////////////////////////////////////// ERC6909 STORAGE //////////////////////////////////////////////////////////////*/ mapping(address => mapping(address => bool)) public isOperator; mapping(address => mapping(uint256 => uint256)) public balanceOf; mapping(address => mapping(address => mapping(uint256 => uint256))) public allowance; /*////////////////////////////////////////////////////////////// ERC6909 LOGIC //////////////////////////////////////////////////////////////*/ function transfer(address receiver, uint256 id, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender][id] -= amount; balanceOf[receiver][id] += amount; emit Transfer(msg.sender, msg.sender, receiver, id, amount); return true; } function transferFrom(address sender, address receiver, uint256 id, uint256 amount) public virtual returns (bool) { if (msg.sender != sender && !isOperator[sender][msg.sender]) { uint256 allowed = allowance[sender][msg.sender][id]; if (allowed != type(uint256).max) allowance[sender][msg.sender][id] = allowed - amount; } balanceOf[sender][id] -= amount; balanceOf[receiver][id] += amount; emit Transfer(msg.sender, sender, receiver, id, amount); return true; } function approve(address spender, uint256 id, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender][id] = amount; emit Approval(msg.sender, spender, id, amount); return true; } function setOperator(address operator, bool approved) public virtual returns (bool) { isOperator[msg.sender][operator] = approved; emit OperatorSet(msg.sender, operator, approved); return true; } /*////////////////////////////////////////////////////////////// ERC165 LOGIC //////////////////////////////////////////////////////////////*/ function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) { return interfaceId == 0x01ffc9a7 // ERC165 Interface ID for ERC165 || interfaceId == 0x0f632fb3; // ERC165 Interface ID for ERC6909 } /*////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address receiver, uint256 id, uint256 amount) internal virtual { balanceOf[receiver][id] += amount; emit Transfer(msg.sender, address(0), receiver, id, amount); } function _burn(address sender, uint256 id, uint256 amount) internal virtual { balanceOf[sender][id] -= amount; emit Transfer(msg.sender, sender, address(0), id, amount); } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @title BitMath /// @dev This library provides functionality for computing bit properties of an unsigned integer library BitMath { /// @notice Returns the index of the most significant bit of the number, /// where the least significant bit is at index 0 and the most significant bit is at index 255 /// @dev The function satisfies the property: /// x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1) /// @param x the value for which to compute the most significant bit, must be greater than 0 /// @return r the index of the most significant bit function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0); unchecked { if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } } /// @notice Returns the index of the least significant bit of the number, /// where the least significant bit is at index 0 and the most significant bit is at index 255 /// @dev The function satisfies the property: /// (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0) /// @param x the value for which to compute the least significant bit, must be greater than 0 /// @return r the index of the least significant bit function leastSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0); unchecked { r = 255; if (x & type(uint128).max > 0) { r -= 128; } else { x >>= 128; } if (x & type(uint64).max > 0) { r -= 64; } else { x >>= 64; } if (x & type(uint32).max > 0) { r -= 32; } else { x >>= 32; } if (x & type(uint16).max > 0) { r -= 16; } else { x >>= 16; } if (x & type(uint8).max > 0) { r -= 8; } else { x >>= 8; } if (x & 0xf > 0) { r -= 4; } else { x >>= 4; } if (x & 0x3 > 0) { r -= 2; } else { x >>= 2; } if (x & 0x1 > 0) r -= 1; } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @title Math functions that do not check inputs or outputs /// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks library UnsafeMath { /// @notice Returns ceil(x / y) /// @dev division by 0 has unspecified behavior, and must be checked externally /// @param x The dividend /// @param y The divisor /// @return z The quotient, ceil(x / y) function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) { unchecked { assembly { z := add(div(x, y), gt(mod(x, y), 0)) } } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.20; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; }
{ "remappings": [ "@ensdomains/=node_modules/@ensdomains/", "@openzeppelin/=lib/openzeppelin-contracts/", "ds-test/=lib/forge-std/lib/ds-test/src/", "forge-gas-snapshot/=lib/forge-gas-snapshot/src/", "forge-std/=lib/forge-std/src/", "hardhat/=node_modules/hardhat/", "solmate/=lib/solmate/src/", "openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/" ], "optimizer": { "enabled": true, "runs": 44444444 }, "metadata": { "useLiteralContent": false, "bytecodeHash": "ipfs", "appendCBOR": true }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "evmVersion": "cancun", "viaIR": true, "libraries": {} }
[{"inputs":[{"internalType":"uint256","name":"controllerGasLimit","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AlreadyUnlocked","type":"error"},{"inputs":[],"name":"CurrenciesOutOfOrderOrEqual","type":"error"},{"inputs":[],"name":"CurrencyNotSettled","type":"error"},{"inputs":[],"name":"DelegateCallNotAllowed","type":"error"},{"inputs":[],"name":"InvalidCaller","type":"error"},{"inputs":[],"name":"InvalidProtocolFee","type":"error"},{"inputs":[],"name":"ManagerLocked","type":"error"},{"inputs":[],"name":"NonZeroNativeValue","type":"error"},{"inputs":[],"name":"PoolNotInitialized","type":"error"},{"inputs":[],"name":"ProtocolFeeCannotBeFetched","type":"error"},{"inputs":[],"name":"SwapAmountCannotBeZero","type":"error"},{"inputs":[],"name":"TickSpacingTooLarge","type":"error"},{"inputs":[],"name":"TickSpacingTooSmall","type":"error"},{"inputs":[],"name":"UnauthorizedDynamicLPFeeUpdate","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":true,"internalType":"uint256","name":"id","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"PoolId","name":"id","type":"bytes32"},{"indexed":true,"internalType":"Currency","name":"currency0","type":"address"},{"indexed":true,"internalType":"Currency","name":"currency1","type":"address"},{"indexed":false,"internalType":"uint24","name":"fee","type":"uint24"},{"indexed":false,"internalType":"int24","name":"tickSpacing","type":"int24"},{"indexed":false,"internalType":"contract IHooks","name":"hooks","type":"address"}],"name":"Initialize","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"id","type":"bytes32"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"int24","name":"tickLower","type":"int24"},{"indexed":false,"internalType":"int24","name":"tickUpper","type":"int24"},{"indexed":false,"internalType":"int256","name":"liquidityDelta","type":"int256"}],"name":"ModifyLiquidity","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"OperatorSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"protocolFeeController","type":"address"}],"name":"ProtocolFeeControllerUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"id","type":"bytes32"},{"indexed":false,"internalType":"uint24","name":"protocolFee","type":"uint24"}],"name":"ProtocolFeeUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"id","type":"bytes32"},{"indexed":false,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"int128","name":"amount0","type":"int128"},{"indexed":false,"internalType":"int128","name":"amount1","type":"int128"},{"indexed":false,"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"indexed":false,"internalType":"uint128","name":"liquidity","type":"uint128"},{"indexed":false,"internalType":"int24","name":"tick","type":"int24"},{"indexed":false,"internalType":"uint24","name":"fee","type":"uint24"}],"name":"Swap","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"uint256","name":"id","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"MAX_TICK_SPACING","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MIN_TICK_SPACING","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"burn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"Currency","name":"currency","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"collectProtocolFees","outputs":[{"internalType":"uint256","name":"amountCollected","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"name":"donate","outputs":[{"internalType":"BalanceDelta","name":"delta","type":"int256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"slot","type":"bytes32"}],"name":"extsload","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"startSlot","type":"bytes32"},{"internalType":"uint256","name":"nSlots","type":"uint256"}],"name":"extsload","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32[]","name":"slots","type":"bytes32[]"}],"name":"extsload","outputs":[{"internalType":"bytes32[]","name":"","type":"bytes32[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32[]","name":"slots","type":"bytes32[]"}],"name":"exttload","outputs":[{"internalType":"bytes32[]","name":"","type":"bytes32[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"slot","type":"bytes32"}],"name":"exttload","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"name":"initialize","outputs":[{"internalType":"int24","name":"tick","type":"int24"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"isOperator","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"mint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"components":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"int256","name":"liquidityDelta","type":"int256"},{"internalType":"bytes32","name":"salt","type":"bytes32"}],"internalType":"struct IPoolManager.ModifyLiquidityParams","name":"params","type":"tuple"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"name":"modifyLiquidity","outputs":[{"internalType":"BalanceDelta","name":"callerDelta","type":"int256"},{"internalType":"BalanceDelta","name":"feesAccrued","type":"int256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"protocolFeeController","outputs":[{"internalType":"contract IProtocolFeeController","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"Currency","name":"currency","type":"address"}],"name":"protocolFeesAccrued","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setOperator","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint24","name":"newProtocolFee","type":"uint24"}],"name":"setProtocolFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IProtocolFeeController","name":"controller","type":"address"}],"name":"setProtocolFeeController","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"Currency","name":"currency","type":"address"}],"name":"settle","outputs":[{"internalType":"uint256","name":"paid","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"components":[{"internalType":"bool","name":"zeroForOne","type":"bool"},{"internalType":"int256","name":"amountSpecified","type":"int256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"}],"internalType":"struct IPoolManager.SwapParams","name":"params","type":"tuple"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"name":"swap","outputs":[{"internalType":"BalanceDelta","name":"swapDelta","type":"int256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"Currency","name":"currency","type":"address"}],"name":"sync","outputs":[{"internalType":"uint256","name":"balance","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"Currency","name":"currency","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"take","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"unlock","outputs":[{"internalType":"bytes","name":"result","type":"bytes"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint24","name":"newDynamicLPFee","type":"uint24"}],"name":"updateDynamicLPFee","outputs":[],"stateMutability":"nonpayable","type":"function"}]
Deployed Bytecode
0x60a0806040526004361015610012575f80fd5b5f3560e01c908162fdd58e14612b905750806301ffc9a714612ad157806307eff0dd14612a98578063095bcdb6146129ee5780630b0d9c0914612960578063156e29f6146128b05780631e2eaeaf14612876578063234266d7146126075780632d7713891461253e57806335fd631a146124d8578063426a84931461245457806348c89491146121ef57806352759651146120d7578063558a729714612000578063598af9e714611f685780635a6bcfda146114b257806360460f0614611478578063695c5bf514610f4d5780636a256b2914610deb5780637e87ce7d14610cbc5780638161b87414610bc45780638da5cb5b14610b7457806397e8cd4e14610b115780639bf6645f14610ad5578063a584119414610a94578063b6363cf214610a03578063dbd035ff146109c3578063f02de3b214610972578063f135baaa14610938578063f2fde38b1461088c578063f3cd914c14610501578063f5298aca146103345763fe99049a14610186575f80fd5b346103305760807ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610330576101bd612bfa565b6101c5612c1d565b90604435917f1b3d7edb2e9c0b0e7c525b20aaaef0f5940d2ed71663c7d39266ecafac72885961027973ffffffffffffffffffffffffffffffffffffffff80606435951693843314158061030d575b610287575b845f52600460205260405f20875f5260205260405f2061023a878254612ea8565b90551693845f52600460205260405f20865f5260205260405f2061025f828254612eb5565b905560408051338152602081019290925290918291820190565b0390a4602060405160018152f35b845f52600560205260405f208233165f5260205260405f20875f5260205260405f2054867fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82036102da575b5050610219565b6102e391612ea8565b855f52600560205260405f208333165f5260205260405f20885f5260205260405f20555f866102d3565b50845f52600360205260405f208233165f5260205260ff60405f20541615610214565b5f80fd5b346103305761034236612c40565b7fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab239291925c156104d9577f1b3d7edb2e9c0b0e7c525b20aaaef0f5940d2ed71663c7d39266ecafac7288596103ef73ffffffffffffffffffffffffffffffffffffffff5f946103bd6103b386613008565b3390848a1661304e565b169233841415806104a2575b6103f4575b8385526004602052604085208686526020526040852061025f828254612ea8565b0390a4005b83855260056020526040852073ffffffffffffffffffffffffffffffffffffffff33168652602052604085208686526020526040852054817fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff820361045b575b50506103ce565b61046491612ea8565b84865260056020526040862073ffffffffffffffffffffffffffffffffffffffff331687526020526040862087875260205260408620558681610454565b5083855260036020526040852073ffffffffffffffffffffffffffffffffffffffff3316865260205260ff604086205416156103c9565b7f54e3ca0d000000000000000000000000000000000000000000000000000000005f5260045ffd5b34610330576101207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103305761053a36612d3c565b60607fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff5c36011261033057604051906060820182811067ffffffffffffffff82111761085f5760405260a4358015158103610330578252602082019060c435825260e4359073ffffffffffffffffffffffffffffffffffffffff8216820361033057604084019182526101043567ffffffffffffffff8111610330576105e3903690600401612e08565b9490937fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab235c156104d957511561083757819060a0822095865f52600660205260405f2095610630876131bd565b6080840196848383868b5173ffffffffffffffffffffffffffffffffffffffff169361065b94613986565b90959198606088015160020b9983511515915173ffffffffffffffffffffffffffffffffffffffff16916040519b6106928d612ccd565b8c5260208c015260408b015260608a015262ffffff166080890152805115155f14997f40e9cecb9f5f1f1c5b9c97dec2917b7ee92e57ba5563708daca94dd84ad7112f60e062ffffff61070b6107b79c60209f9b6107a49c610817575173ffffffffffffffffffffffffffffffffffffffff16976149c7565b9392988291926107e8575b505073ffffffffffffffffffffffffffffffffffffffff6040840151169260606fffffffffffffffffffffffffffffffff60a08301511691015160020b90604051943386528a60801d600f0b60208701528a600f0b60408701526060860152608085015260a08401521660c0820152a28673ffffffffffffffffffffffffffffffffffffffff8a5116613b93565b809491946107bf575b5050823391613299565b604051908152f35b73ffffffffffffffffffffffffffffffffffffffff6107e19251169083613299565b84806107ad565b73ffffffffffffffffffffffffffffffffffffffff165f5260206001905260405f209081540190555f80610716565b6020015173ffffffffffffffffffffffffffffffffffffffff16976149c7565b7fbe8b8507000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b346103305760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610330577fffffffffffffffffffffffff00000000000000000000000000000000000000006108e4612bfa565b73ffffffffffffffffffffffffffffffffffffffff5f54916109098284163314612ec2565b1691829116175f55337f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f80a3005b346103305760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610330576004355c5f5260205ff35b34610330575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033057602073ffffffffffffffffffffffffffffffffffffffff60025416604051908152f35b34610330576109d136612e36565b604060045f3760051b604001809160208060405b833554815201910190828110156109ff57602080916109e5565b825ff35b346103305760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033057610a3a612bfa565b73ffffffffffffffffffffffffffffffffffffffff610a57612c1d565b91165f52600360205273ffffffffffffffffffffffffffffffffffffffff60405f2091165f52602052602060ff60405f2054166040519015158152f35b346103305760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103305760206107b7610ad0612bfa565b612f9f565b3461033057610ae336612e36565b604060045f3760051b604001809160208060405b83355c815201910190828110156109ff5760208091610af7565b346103305760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103305773ffffffffffffffffffffffffffffffffffffffff610b5d612bfa565b165f526001602052602060405f2054604051908152f35b34610330575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033057602073ffffffffffffffffffffffffffffffffffffffff5f5416604051908152f35b346103305760607ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033057610bfb612bfa565b610c03612c1d565b9060443573ffffffffffffffffffffffffffffffffffffffff600254163303610c94576020926107b79180610c8c575073ffffffffffffffffffffffffffffffffffffffff81165f526001845260405f20549283915b73ffffffffffffffffffffffffffffffffffffffff81165f526001865260405f20610c85848254612ea8565b905561313e565b928391610c59565b7f48f5c3ed000000000000000000000000000000000000000000000000000000005f5260045ffd5b346103305760c07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033057610cf436612d3c565b610cfc612d2a565b9073ffffffffffffffffffffffffffffffffffffffff600254163303610c9457623e900082106103e9610fff8416101615610dc357602060a07fe9c42593e71f84403b84352cd168d693e2c9fcd1fdbcc3feb21d92b43e6696f9922092835f526006825260405f20610d6d816131bd565b805479ffffff00000000000000000000000000000000000000000000008360b81b16907fffffffffffff000000ffffffffffffffffffffffffffffffffffffffffffffff1617905562ffffff60405191168152a2005b7fba97f838000000000000000000000000000000000000000000000000000000005f5260045ffd5b60207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033057610e1d612bfa565b7fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab235c156104d95773ffffffffffffffffffffffffffffffffffffffff8116610e78576020906107b734915b610e7183613008565b339161304e565b34610f25577f1e0745a7db1623981f0b2a5d4232364c00787266eb75ad546f190e6cebe9bd955f528060205260405f205c908115610efd57817fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60209314610ef6575b610ef06107b791610eeb84612f9f565b612ea8565b91610e68565b505f610edb565b7f8774be48000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f19d245cf000000000000000000000000000000000000000000000000000000005f5260045ffd5b346103305760e07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033057610f8536612d3c565b60a43573ffffffffffffffffffffffffffffffffffffffff81168082036103305760c43567ffffffffffffffff811161033057610fc6903690600401612e08565b610fce6132d7565b6060850192617fff845160020b13611450576001845160020b126114285773ffffffffffffffffffffffffffffffffffffffff86511692602087019373ffffffffffffffffffffffffffffffffffffffff855116111561140057608087019473ffffffffffffffffffffffffffffffffffffffff86511695604089019661105b62ffffff89511682613672565b156113d5575061107062ffffff885116613730565b93815173ffffffffffffffffffffffffffffffffffffffff811690813303611311575b505060a08a20936110a38b61374d565b9a9050855f52600660205260405f2090815473ffffffffffffffffffffffffffffffffffffffff166112e9576110d890614654565b9a8b9760d01b7cffffff00000000000000000000000000000000000000000000000000001690848960a01b76ffffff000000000000000000000000000000000000000016179060b81b79ffffff0000000000000000000000000000000000000000000000161717905582519173ffffffffffffffffffffffffffffffffffffffff831692833314159c7f3fd553db44f207b1f41348cfc4d251860814af9eadc470e8e7895e4d120511f49960809960209f9662ffffff9673ffffffffffffffffffffffffffffffffffffffff989689979688976111e7575b5050505050505116985116985116925160020b915116916040519384528984015260408301526060820152a36040519060020b8152f35b611000166111f6575b806111b0565b6112ad6112d9926112de96604051966020947fa910f80f00000000000000000000000000000000000000000000000000000000899687015233602487015261128b604487018c73ffffffffffffffffffffffffffffffffffffffff6080809282815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b60e486015260020b610104850152610120610124850152610144840191612f61565b037fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08101845283612ce9565b613d37565b508e8d8180806111f0565b7f7983c051000000000000000000000000000000000000000000000000000000005f5260045ffd5b61200016611320575b80611093565b6113ce90604051907f3440d8200000000000000000000000000000000000000000000000000000000060208301523360248301526113ac8d604484019073ffffffffffffffffffffffffffffffffffffffff6080809282815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b8360e48301526101006101048301526112d9826112ad61012482018c8b612f61565b508a61131a565b7fe65af6a0000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b7feaa6c6eb000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f16fe7696000000000000000000000000000000000000000000000000000000005f5260045ffd5b7fb02b5dc2000000000000000000000000000000000000000000000000000000005f5260045ffd5b34610330575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610330576020604051617fff8152f35b34610330576101407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610330576114eb36612d3c565b60807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff5c360112610330576040519061152282612c95565b60a4358060020b810361033057825260c4358060020b810361033057602083015260e435604083015260608201916101043583526101243567ffffffffffffffff811161033057611577903690600401612e08565b907fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab235c156104d95760a0842091825f52600660205260405f20916115ba836131bd565b60808601518573ffffffffffffffffffffffffffffffffffffffff821691823303611e8a575b5090505160020b93602086015160020b956115fe6040820151613431565b96606089015160020b99516040519a6116168c612cb1565b338c528860208d01528260408d015289600f0b60608d015260808c015260a08b01525f9080881215611e5b577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff276188812611e2f57620d89e88113611e0457604051986116808a612c95565b5f8a525f60208b01525f60408b01525f60608b015280600f0b611b2b575b60048801988060020b5f528960205260405f20998360020b5f5260205260405f20895460a01c60020b8281125f14611ad9575060028060018d0154600184015490039c015491015490039c5b60a073ffffffffffffffffffffffffffffffffffffffff82511691015160265283600652816003525f52603a600c205f6026525f526006890160205260405f20986fffffffffffffffffffffffffffffffff8a54169a83600f0b155f14611a7c578b15611a545761179560409f6118699c61178f9161187b9f5b6001830195611787600261177b848a548503613ebb565b95019283548503613ebb565b965555613008565b91613008565b6fffffffffffffffffffffffffffffffff169060801b179b5f84600f0b126119ea575b5082600f0b6118b3575b505050506117e96117da8960801d8360801d01613431565b9189600f0b90600f0b01613431565b6fffffffffffffffffffffffffffffffff169060801b1791815160020b90602083015160020b8b840151908c5193845260208401528b8301527f541c041c2cce48e614b3de043c9280f06b6164c0a1741649e2de3c3d375f797460603393a38773ffffffffffffffffffffffffffffffffffffffff608082015116613520565b80949194611887575b50833391613299565b82519182526020820152f35b6118ad9073ffffffffffffffffffffffffffffffffffffffff6080840151169083613299565b85611872565b809192939450548060a01c60020b9073ffffffffffffffffffffffffffffffffffffffff16908381125f1461191b5750505091611909916119036118f961190e956141cc565b91600f0b926141cc565b906145a3565b613431565b60801b5b8a8080806117c2565b948091939295125f146119b6576fffffffffffffffffffffffffffffffff926119736119096119899461196061190960039661195a8b600f0b916141cc565b876145a3565b9361196e89600f0b926141cc565b61451a565b84169060801b17940192600f0b828454166145f4565b167fffffffffffffffffffffffffffffffff00000000000000000000000000000000825416179055611912565b91506119d39350916119cd6118f9611909946141cc565b9061451a565b6fffffffffffffffffffffffffffffffff16611912565b808f9151611a2a575b0151611a00575b8e6117b8565b611a25848260049160020b5f52016020525f6002604082208281558260018201550155565b6119fa565b611a4f848460049160020b5f52016020525f6002604082208281558260018201550155565b6119f3565b7faefeb924000000000000000000000000000000000000000000000000000000005f5260045ffd5b61179560409f6118699c61178f9161187b9f6fffffffffffffffffffffffffffffffff611aac8a600f0b836145f4565b167fffffffffffffffffffffffffffffffff00000000000000000000000000000000845416178355611764565b909a908413611aff5760028060018d0154600184015490039c015491015490039c6116ea565b99600260018b015460018d01549003600183015490039b81808d0154910154900391015490039c6116ea565b8860020b5f5260048801602052886fffffffffffffffffffffffffffffffff60405f20805490611b85838316928d611b6688600f0b866145f4565b9415968787871615141597611dd5575b505086600f0b9060801d613b4c565b60801b821790551660208c01528a528160020b5f526004880160205260405f208054906fffffffffffffffffffffffffffffffff8216611bc884600f0b826145f4565b901592836fffffffffffffffffffffffffffffffff831615141593611dae575b84600f0b9060801d600f0b03916f7fffffffffffffffffffffffffffffff83137fffffffffffffffffffffffffffffffff80000000000000000000000000000000841217611d8157826fffffffffffffffffffffffffffffffff935060801b821790551660608c015260408b0152898c5f83600f0b1215611ca9575b5051611c8f575b60408a01511561169e57611c8a60808d015160020b8360058b01614193565b61169e565b611ca460808d015160020b8a60058b01614193565b611c6b565b60016fffffffffffffffffffffffffffffffff602060808294015160020b940151169280807ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff2761805028180620d89e80502030501810416809111611d55576fffffffffffffffffffffffffffffffff60608c01511611611d2957898c611c64565b507fb8e3c385000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b897fb8e3c385000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b8b5460a01c60020b8613611be85760018c0154600184015560028c01546002840155611be8565b815460a01c60020b1215611dea575b8f611b76565b80600160029201546001860155015460028401558d611de4565b7f1ad777f8000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b877fd5e2f7ab000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b877fc4433ed5000000000000000000000000000000000000000000000000000000005f5260045260245260445ffd5b5f604083015113808091611f5b575b15611eed575050611ee3916112d9896112ad87876040519687947f259982e50000000000000000000000000000000000000000000000000000000060208701523360248701613377565b505b8785816115e0565b159081611f4d575b50611f02575b5050611ee5565b611f45916112d9896112ad87876040519687947f21d0ee700000000000000000000000000000000000000000000000000000000060208701523360248701613377565b508785611efb565b61020091501615158a611ef5565b5061080082161515611e99565b346103305760607ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033057611f9f612bfa565b73ffffffffffffffffffffffffffffffffffffffff611fbc612c1d565b91165f52600560205273ffffffffffffffffffffffffffffffffffffffff60405f2091165f5260205260405f206044355f52602052602060405f2054604051908152f35b346103305760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033057612037612bfa565b602435908115158092036103305773ffffffffffffffffffffffffffffffffffffffff90335f52600360205260405f208282165f5260205260405f207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0081541660ff851617905560405192835216907fceb576d9f15e4e200fdb5096d64d5dfd667e16def20c1eefd14256d8e3faa26760203392a3602060405160018152f35b346103305760c07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103305761210f36612d3c565b612117612d2a565b906280000062ffffff604083015116148015906121cb575b6121a35760a09061213f8361333e565b205f52600660205260405f2090612155826131bd565b81547fffffff000000ffffffffffffffffffffffffffffffffffffffffffffffffffff1660d09190911b7cffffff000000000000000000000000000000000000000000000000000016179055005b7f30d21641000000000000000000000000000000000000000000000000000000005f5260045ffd5b5073ffffffffffffffffffffffffffffffffffffffff60808201511633141561212f565b346103305760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103305760043567ffffffffffffffff81116103305761223e903690600401612e08565b6122466132d7565b7fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab235c61242c576122d2915f9160017fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab235d60405193849283927f91dd7346000000000000000000000000000000000000000000000000000000008452602060048501526024840191612f61565b038183335af1908115612421575f916123a7575b507f7d4b3164c6e45b97e7d87b7125a44c5828d005af88f9d751cfd78729c5d99a0b5c61237f5760406020915f7fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab235d7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f835194859381855280519182918282880152018686015e5f85828601015201168101030190f35b7f5212cba1000000000000000000000000000000000000000000000000000000005f5260045ffd5b90503d805f833e6123b88183612ce9565b8101906020818303126103305780519067ffffffffffffffff8211610330570181601f82011215610330578051906123ef82612f27565b926123fd6040519485612ce9565b8284526020838301011161033057815f9260208093018386015e83010152816122e6565b6040513d5f823e3d90fd5b7f5090d6c6000000000000000000000000000000000000000000000000000000005f5260045ffd5b346103305773ffffffffffffffffffffffffffffffffffffffff61247736612c40565b91929092335f52600560205260405f208282165f5260205260405f20845f526020528260405f205560405192835216907fb3fd5071835887567a0671151121894ddccc2842f1d10bedad13e0d17cace9a760203392a4602060405160018152f35b346103305760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103305760043560205f5260243560051b8060205260400180916001602060405b8354815201910190828110156109ff576020600191612524565b346103305760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103305760043573ffffffffffffffffffffffffffffffffffffffff81168091036103305760207fb4bd8ef53df690b9943d3318996006dbb82a25f54719d8c8035b516a2a5b8acc916125d473ffffffffffffffffffffffffffffffffffffffff5f54163314612ec2565b807fffffffffffffffffffffffff00000000000000000000000000000000000000006002541617600255604051908152a1005b34610330576101007ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103305761264036612d3c565b60c4359060a43560e43567ffffffffffffffff811161033057612667903690600401612e08565b9190937fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab235c156104d95760a084205f52600660205260405f20946126aa866131bd565b6080850194855173ffffffffffffffffffffffffffffffffffffffff81169081330361281e575b50506fffffffffffffffffffffffffffffffff6003880154169586156127f6576020976126fd86613008565b5f0361270886613008565b5f036fffffffffffffffffffffffffffffffff169060801b1797866127dd575b856127c2575b505061273b338884613299565b519273ffffffffffffffffffffffffffffffffffffffff841693843303612767575b8888604051908152f35b601016612775575b8061275d565b6127b6956112d9936112ad926040519788957fe1b4af69000000000000000000000000000000000000000000000000000000008d8801523360248801613203565b5082808080808061276f565b6127ce60029187613dfa565b9101908154019055888061272e565b6127e78188613dfa565b60018301908154019055612728565b7fa74f97ab000000000000000000000000000000000000000000000000000000005f5260045ffd5b60201661282c575b806126d1565b6040517fb6a8b0fa00000000000000000000000000000000000000000000000000000000602082015261286f916112d9826112ad8a888a8c8a3360248801613203565b5087612826565b346103305760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033057600435545f5260205ff35b34610330576128be36612c40565b90917fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab235c156104d9577f1b3d7edb2e9c0b0e7c525b20aaaef0f5940d2ed71663c7d39266ecafac7288596103ef73ffffffffffffffffffffffffffffffffffffffff5f9361293d61292e87613008565b8603600f0b3390848a1661304e565b16938484526004602052604084208685526020526040842061025f828254612eb5565b346103305760607ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033057612997612bfa565b61299f612c1d565b604435907fc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab235c156104d9576129ec926129e76129da84613008565b5f03600f0b33908361304e565b61313e565b005b346103305773ffffffffffffffffffffffffffffffffffffffff612a1136612c40565b91929092335f52600460205260405f20845f5260205260405f20612a36848254612ea8565b90551690815f52600460205260405f20835f5260205260405f20612a5b828254612eb5565b9055604080513380825260208201939093527f1b3d7edb2e9c0b0e7c525b20aaaef0f5940d2ed71663c7d39266ecafac7288599181908101610279565b34610330575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033057602060405160018152f35b346103305760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610330576004357fffffffff00000000000000000000000000000000000000000000000000000000811680910361033057807f01ffc9a70000000000000000000000000000000000000000000000000000000060209214908115612b66575b506040519015158152f35b7f0f632fb30000000000000000000000000000000000000000000000000000000091501482612b5b565b346103305760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103305760209073ffffffffffffffffffffffffffffffffffffffff612bdf612bfa565b165f526004825260405f206024355f52825260405f20548152f35b6004359073ffffffffffffffffffffffffffffffffffffffff8216820361033057565b6024359073ffffffffffffffffffffffffffffffffffffffff8216820361033057565b7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc60609101126103305760043573ffffffffffffffffffffffffffffffffffffffff8116810361033057906024359060443590565b6080810190811067ffffffffffffffff82111761085f57604052565b60c0810190811067ffffffffffffffff82111761085f57604052565b60a0810190811067ffffffffffffffff82111761085f57604052565b90601f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0910116810190811067ffffffffffffffff82111761085f57604052565b60a4359062ffffff8216820361033057565b7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc60a09101126103305760405190612d7382612ccd565b8160043573ffffffffffffffffffffffffffffffffffffffff8116810361033057815260243573ffffffffffffffffffffffffffffffffffffffff8116810361033057602082015260443562ffffff811681036103305760408201526064358060020b81036103305760608201526084359073ffffffffffffffffffffffffffffffffffffffff821682036103305760800152565b9181601f840112156103305782359167ffffffffffffffff8311610330576020838186019501011161033057565b9060207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc8301126103305760043567ffffffffffffffff811161033057826023820112156103305780600401359267ffffffffffffffff84116103305760248460051b83010111610330576024019190565b91908203918211611d8157565b91908201809211611d8157565b15612ec957565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600c60248201527f554e415554484f52495a454400000000000000000000000000000000000000006044820152fd5b67ffffffffffffffff811161085f57601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01660200190565b601f82602094937fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe093818652868601375f8582860101520116010190565b90612fa9826138ef565b9182908315612fe0575b7f1e0745a7db1623981f0b2a5d4232364c00787266eb75ad546f190e6cebe9bd955f5260205260405f205d565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9150612fb3565b6f8000000000000000000000000000000081101561302657600f0b90565b6393dafdf15f526004601cfd5b9190915f8382019384129112908015821691151617611d8157565b90600f0b91821561313957805f528160205261306f60405f205c9384613033565b92836130e957507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f7d4b3164c6e45b97e7d87b7125a44c5828d005af88f9d751cfd78729c5d99a0b5c017f7d4b3164c6e45b97e7d87b7125a44c5828d005af88f9d751cfd78729c5d99a0b5d5b5f5260205260405f205d565b6130dd5760017f7d4b3164c6e45b97e7d87b7125a44c5828d005af88f9d751cfd78729c5d99a0b5c017f7d4b3164c6e45b97e7d87b7125a44c5828d005af88f9d751cfd78729c5d99a0b5d6130dd565b505050565b73ffffffffffffffffffffffffffffffffffffffff811661317657505f80809381935af11561316957565b63f4b3b1bc5f526004601cfd5b60105f60449260209582956014526034526fa9059cbb00000000000000000000000082525af13d1560015f51141716156131b0575f603452565b63f27f64e45f526004601cfd5b5473ffffffffffffffffffffffffffffffffffffffff16156131db57565b7f486aa307000000000000000000000000000000000000000000000000000000005f5260045ffd5b919261327e6101209473ffffffffffffffffffffffffffffffffffffffff613296999794168552602085019073ffffffffffffffffffffffffffffffffffffffff6080809282815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b60c083015260e0820152816101008201520191612f61565b90565b9073ffffffffffffffffffffffffffffffffffffffff60206132d594936132c885848351168660801d9061304e565b01511690600f0b9061304e565b565b73ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000006ff7ef1e597224af014e588a35a5f4bfc51f853a16300361331657565b7f0d89438e000000000000000000000000000000000000000000000000000000005f5260045ffd5b62ffffff620f424091161161334f57565b7ffc5bee12000000000000000000000000000000000000000000000000000000005f5260045ffd5b9061329695936133f46101609473ffffffffffffffffffffffffffffffffffffffff61342394168552602085019073ffffffffffffffffffffffffffffffffffffffff6080809282815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b8051600290810b60c08501526020820151900b60e0840152604081015161010084015260600151610120830152565b816101408201520191612f61565b806f800000000000000000000000000000000160801c15613459576393dafdf15f526004601cfd5b600f0b90565b91610180936134dd61350c9273ffffffffffffffffffffffffffffffffffffffff6132969a9895168652602086019073ffffffffffffffffffffffffffffffffffffffff6080809282815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b8051600290810b60c08601526020820151900b60e0850152604081015161010085015260600151610120840152565b610140820152816101608201520191612f61565b929593945f9573ffffffffffffffffffffffffffffffffffffffff8516331461366857875f6040860151135f146135fa576104008616613563575b505050505050565b6135ee969897506135db926135e7969594926135af926040519687957f5a2a8100000000000000000000000000000000000000000000000000000000006020880152336024880161345f565b037fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08101835282612ce9565b60028216151591614600565b8092614617565b915f808080808061355b565b9493929190610100851661361057505050505050565b6135ee96985085975061365c92916135af916135e7976040519687957f8db2b652000000000000000000000000000000000000000000000000000000006020880152336024880161345f565b60018216151591614600565b505f955050505050565b608081161580613724575b6136fa57604081161580613718575b6136fa576104008116158061370c575b6136fa5761010081161580613700575b6136fa5773ffffffffffffffffffffffffffffffffffffffff81166136da575062ffffff1662800000141590565b613fff1615908115916136eb575090565b62800000915062ffffff161490565b50505f90565b506001811615156136ac565b5060028116151561369c565b5060048116151561368c565b5060088116151561367d565b6280000062ffffff821614613748576132968161333e565b505f90565b5f915f9173ffffffffffffffffffffffffffffffffffffffff6002541680613773575050565b91935091505a7f00000000000000000000000000000000000000000000000000000000000000008091106138c7575f9283809360405161382860208201947f553bfc37000000000000000000000000000000000000000000000000000000008652602483019073ffffffffffffffffffffffffffffffffffffffff6080809282815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b60a4815261383760c482612ce9565b5193f13d156138bf573d9061384b82612f27565b916138596040519384612ce9565b82523d5f602084013e5b1580156138b4575b6138ad576020015162ffffff8116908181149081613895575b501561388f57600191565b505f8091565b90506103e9610fff623e90008410921610165f613884565b505f905f90565b50602081511161386b565b606090613863565b7f1ee49702000000000000000000000000000000000000000000000000000000005f5260045ffd5b73ffffffffffffffffffffffffffffffffffffffff168061390f57504790565b6020602491604051928380927f70a082310000000000000000000000000000000000000000000000000000000082523060048301525afa908115612421575f91613957575090565b90506020813d60201161397e575b8161397260209383612ce9565b81010312610330575190565b3d9150613965565b949192945f945f9460208101519773ffffffffffffffffffffffffffffffffffffffff84163314613b3f57608084166139c1575b5050505050565b613ab3613a63613aad876135af6040956280000098613a9962ffffff9989519788967f575e24b4000000000000000000000000000000000000000000000000000000006020890152336024890152604488019073ffffffffffffffffffffffffffffffffffffffff6080809282815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b8051151560e487015260208101516101048701526040015173ffffffffffffffffffffffffffffffffffffffff16610124860152565b610140610144850152610164840191612f61565b85613d37565b9401511614613b33575b600816613ace575b808080806139ba565b604001519250608083901d600f0b8015613ac557613aef905f861295613033565b9315613b2b575f84135b613b03575f613ac5565b7ffa0b71d6000000000000000000000000000000000000000000000000000000005f5260045ffd5b5f8412613af9565b60608201519350613abd565b505f965086955050505050565b90600f0b90600f0b01907fffffffffffffffffffffffffffffffff8000000000000000000000000000000082126f7fffffffffffffffffffffffffffffff831317611d8157565b9196959394929473ffffffffffffffffffffffffffffffffffffffff83163314613d2a578460801d94600f0b938860408516613c52575b50505050505f9481600f0b15801590613c46575b613bea575b5050509190565b613c219395505f60208201511290511515145f14613c29576fffffffffffffffffffffffffffffffff169060801b175b8093614617565b5f8080613be3565b906fffffffffffffffffffffffffffffffff169060801b17613c1a565b5082600f0b1515613bde565b613d0e613d1a946135af61190995613d20999895613cf3613a63966040519788967fb47b2fb1000000000000000000000000000000000000000000000000000000006020890152336024890152604488019073ffffffffffffffffffffffffffffffffffffffff6080809282815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b8c610144850152610160610164850152610184840191612f61565b60048216151591614600565b90613b4c565b5f80808088613bca565b5050505050909150905f90565b5f80939281926020825192019586915af115613ddf57604051917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0603f3d011683016040523d83527fffffffff00000000000000000000000000000000000000000000000000000000803d60208601905f823e51925116911603613db757565b7f1e048e1d000000000000000000000000000000000000000000000000000000005f5260045ffd5b3d15613ded573d5f803e3d5ffd5b6336bc48c55f526004601cfd5b908160801b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7001000000000000000000000000000000008409928280851094039380850394858411156103305714613eb45770010000000000000000000000000000000082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b5091500490565b90808202917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8282099183808410930392808403938470010000000000000000000000000000000011156103305714613f3457700100000000000000000000000000000000910990828211900360801b910360801c1790565b50505060801c90565b90808202917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff828209918380841093039280840393846c0100000000000000000000000011156103305714613fae576c01000000000000000000000000910990828211900360a01b910360601c1790565b50505060601c90565b818102907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff83820990828083109203918083039283620f424011156103305714614036577fde8f6cefed634549b62c77574f722e1ac57e23f24d8fd5cb790fb65668c2613993620f4240910990828211900360fa1b910360061c170290565b5050620f424091500490565b908160601b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6c010000000000000000000000008409928280851094039380850394858411156103305714613eb4576c0100000000000000000000000082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b91818302917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff81850993838086109503948086039586851115610330571461418b579082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b505091500490565b91908181076141b95705908160081d5f52602052600160ff60405f2092161b8154189055565b63d4d8f3e65f526020526040526044601cfd5b8060ff1d81810118620d89e8811161450d5763ffffffff91600182167001fffcb933bd6fad37aa2d162d1a594001027001000000000000000000000000000000001891600281166144f1575b600481166144d5575b600881166144b9575b6010811661449d575b60208116614481575b60408116614465575b60808116614449575b610100811661442d575b6102008116614411575b61040081166143f5575b61080081166143d9575b61100081166143bd575b61200081166143a1575b6140008116614385575b6180008116614369575b62010000811661434d575b620200008116614332575b620400008116614317575b62080000166142fe575b5f126142d7575b0160201c90565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff046142d0565b6b048a170391f7dc42444e8fa290910260801c906142c9565b6d2216e584f5fa1ea926041bedfe9890920260801c916142bf565b916e5d6af8dedb81196699c329225ee6040260801c916142b4565b916f09aa508b5b7a84e1c677de54f3e99bc90260801c916142a9565b916f31be135f97d08fd981231505542fcfa60260801c9161429e565b916f70d869a156d2a1b890bb3df62baf32f70260801c91614294565b916fa9f746462d870fdf8a65dc1f90e061e50260801c9161428a565b916fd097f3bdfd2022b8845ad8f792aa58250260801c91614280565b916fe7159475a2c29b7443b29c7fa6e889d90260801c91614276565b916ff3392b0822b70005940c7a398e4b70f30260801c9161426c565b916ff987a7253ac413176f2b074cf7815e540260801c91614262565b916ffcbe86c7900a88aedcffc83b479aa3a40260801c91614258565b916ffe5dee046a99a2a811c461f1969c30530260801c9161424e565b916fff2ea16466c96a3843ec78b326b528610260801c91614245565b916fff973b41fa98c081472e6896dfb254c00260801c9161423c565b916fffcb9843d60f6159c9db58835c9266440260801c91614233565b916fffe5caca7e10e4e61c3624eaa0941cd00260801c9161422a565b916ffff2e50f5f656932ef12357cf3c7fdcc0260801c91614221565b916ffff97272373d413259a46990580e213a0260801c91614218565b63ce8ef7fc5f526004601cfd5b5f83600f0b125f1461455757916145529161329693038060ff1d90810118905f036fffffffffffffffffffffffffffffffff16613f3d565b615a16565b906c0100000000000000000000000060019161459e946fffffffffffffffffffffffffffffffff1693038060ff1d908101186145938185613f3d565b930915151601615a16565b5f0390565b915f81600f0b125f146145d3579161455291613296935f036fffffffffffffffffffffffffffffffff1691615ad0565b916145529161459e936fffffffffffffffffffffffffffffffff1691615a2b565b01908160801c61302657565b9061460a91613d37565b9015613748576040015190565b61463a9061462c8360801d8260801d03613431565b92600f0b90600f0b03613431565b6fffffffffffffffffffffffffffffffff169060801b1790565b73fffd8963efd1fc6a506488495d951d51639616827ffffffffffffffffffffffffffffffffffffffffffffffffffffffffefffd895d8201116149835777ffffffffffffffffffffffffffffffffffffffff000000008160201b16806fffffffffffffffffffffffffffffffff811160071b90811c67ffffffffffffffff811160061b90811c63ffffffff811160051b90811c61ffff811160041b90811c9060ff821160031b91821c92600f841160021b93841c94600160038711811b96871c1196171717171717179060808210155f14614979577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8182011c5b800280607f1c8160ff1c1c800280607f1c8160ff1c1c800280607f1c8160ff1c1c800280607f1c8160ff1c1c800280607f1c8160ff1c1c800280607f1c8160ff1c1c80029081607f1c8260ff1c1c80029283607f1c8460ff1c1c80029485607f1c8660ff1c1c80029687607f1c8860ff1c1c80029889607f1c8a60ff1c1c80029a8b607f1c8c60ff1c1c80029c8d80607f1c9060ff1c1c800260cd1c6604000000000000169d60cc1c6608000000000000169c60cb1c6610000000000000169b60ca1c6620000000000000169a60c91c6640000000000000169960c81c6680000000000000169860c71c670100000000000000169760c61c670200000000000000169660c51c670400000000000000169560c41c670800000000000000169460c31c671000000000000000169360c21c672000000000000000169260c11c674000000000000000169160c01c67800000000000000016907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff800160401b1717171717171717171717171717693627a301d71055774c85027ffffffffffffffffffffffffffffffffffd709b7e5480fba5a50fed5e62ffc556810160801d60020b906fdb2df09e81959a81455e260799a0632f0160801d60020b918282145f146149365750905090565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff61496a846141cc565b1611614974575090565b905090565b81607f031b61474e565b6331efafe85f526004601cfd5b811561499a570490565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b905f6040516149d581612cb1565b5f815260208101905f825260408101955f875260608201945f865260808301915f83525f60a08501528398885493602084015115986fffffffffffffffffffffffffffffffff60038c015416928a155f14615a07575f610fff8860b81c16995b60408801518a52528673ffffffffffffffffffffffffffffffffffffffff1690528560a01c60020b905288155f146159fc5760018a0154905b5260a085018190526080830151624000008116156159ed5762bfffff16614a948161333e565b61ffff87166159cc57905b81945f604086015112928315978880996159bb575b6159935760408701511561597d57505089615909576060850173ffffffffffffffffffffffffffffffffffffffff8151168273ffffffffffffffffffffffffffffffffffffffff168110156158c457505173ffffffffffffffffffffffffffffffffffffffff166401000276a381111561589957505b60405160805260e060805101608051811067ffffffffffffffff82111761085f576040525f608051525f602060805101525f604060805101525f606060805101525f6080805101525f60a060805101525f60c060805101525b8b5115801561585c575b61570c5773ffffffffffffffffffffffffffffffffffffffff60408d0151166080515260608c015160020b855160020b90815f818307129105038c8c155f1461547e575060ff8116918d60056001851b918460081d60010b5f52016020527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60405f209180010190541691821592831593845f146154495781955f91610330577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff27618968370010000000000000000000000000000000060ff95101561543a575b508068010000000000000000600292101561542c575b64010000000081101561541e575b62010000811015615410575b610100811015615402575b60108110156153f4575b60048110156153e7575b10156153da575b031660020b900360020b0260020b5b905b15156040608051015260020b806020608051015213156153ad575b620d89e86020608051015160020b121561539d575b8b73ffffffffffffffffffffffffffffffffffffffff604081614d2e6020608051015160020b6141cc565b169283606060805101520151169073ffffffffffffffffffffffffffffffffffffffff60608801511690818d158183101891180218908d6fffffffffffffffffffffffffffffffff60a08201511690519062ffffff8a169273ffffffffffffffffffffffffffffffffffffffff8516811015915f84125f146151e35784620f424003614dbc81865f03613fb7565b9684156151b157614dce838583615a2b565b955b8689106150b9575073ffffffffffffffffffffffffffffffffffffffff9750958691620f424082036150aa575050845b935b1561509c5791614e1b92038060ff1d9081011890613f3d565b905b60c0608051015260a060805101526080805101521660408d0152865f1461505c57614e4d60a06080510151615a16565b8c51038c5260208c01805190614e7261455260808051015160c0608051015190612eb5565b915f8382039312818412811691841390151617611d8157525b61ffff8816615029575b6fffffffffffffffffffffffffffffffff60a08d01511680615009575b5073ffffffffffffffffffffffffffffffffffffffff60408d01511673ffffffffffffffffffffffffffffffffffffffff606060805101511681145f14614fcb575060406080510151614f1a575b89156020608051015160020b0360020b60608d0152614b83565b89614fa2576fffffffffffffffffffffffffffffffff614f898d8d60808201519060046002820154915b6020608051015160020b60020b5f520160205260405f2091600183019081549003905560028201908154900390555460801d908d15614f94575b60a0015183166145f4565b1660a08d0152614f00565b5f91909103600f0b90614f7e565b6fffffffffffffffffffffffffffffffff614f898d8d6001810154906004608084015191614f44565b73ffffffffffffffffffffffffffffffffffffffff60805151168103614ff2575b50614b83565b614ffb90614654565b60020b60608d01525f614fec565b6150199060c06080510151613dfa565b60808d019081510190525f614eb2565b97620f424060808051015161ffff8a169060c06080510151010204908160c060805101510360c060805101520197614e95565b61507260808051015160c0608051015101615a16565b8c51018c5260208c01615095815161508f60a06080510151615a16565b90613033565b9052614e8b565b6150a592615ad0565b614e1b565b6150b49187615b65565b614e00565b95505050809450158115176151a45773ffffffffffffffffffffffffffffffffffffffff948215615140576150ef908583615c03565b935b84808284861561510f5761510492615a2b565b8095015f0393614e02565b9050038060ff1d9081011860016c010000000000000000000000006151348386613f3d565b92850915151601615104565b61517c90615177908781116151825761516f906fffffffffffffffffffffffffffffffff88169060601b614990565b878416612eb5565b615c91565b936150f1565b61519f906fffffffffffffffffffffffffffffffff881690614042565b61516f565b634f2461b85f526004601cfd5b8084038060ff1d9081011860016c010000000000000000000000006151d68387613f3d565b9286091515160195614dd0565b909491939291841561538c576152038682038060ff1d9081011883613f3d565b925b83811061527e57509073ffffffffffffffffffffffffffffffffffffffff956152499280965b1561524e579061523b9291615a2b565b809380620f42400391615b65565b614e1d565b6c0100000000000000000000000090600192038060ff1d908101186152738185613f3d565b93091515160161523b565b9250508181158615176151a45784156153625773ffffffffffffffffffffffffffffffffffffffff81116153095760601b6fffffffffffffffffffffffffffffffff82168082061515910401905b818611156152fc578573ffffffffffffffffffffffffffffffffffffffff615249938180991603165b809661522b565b634323a5555f526004601cfd5b6fffffffffffffffffffffffffffffffff8216615334816c01000000000000000000000000846140f4565b91811561499a576c010000000000000000000000009009615356575b906152cc565b60010180615350575f80fd5b9085615387615249938373ffffffffffffffffffffffffffffffffffffffff99615b8e565b6152f5565b615397828288615ad0565b92615205565b620d89e860206080510152614d03565b7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff2761860206080510152614cee565b9060018391011690614cc2565b928101841692811c614cbb565b60049384018516931c614cb1565b60089384018516931c614ca7565b60109384018516931c614c9c565b60209384018516931c614c90565b60409384018516931c614c82565b60809350831c90506002614c6c565b50507ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff276189360020b900360020b0260020b614cd1565b90600101918260020b9260058160ff16938560081d60010b5f52016020527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff600160ff60405f2093161b011990541692831593841593845f146156d2578195610330577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff276189560ff9283906fffffffffffffffffffffffffffffffff8116156156c8575050607f5b67ffffffffffffffff8216156156be577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc00183165b63ffffffff8216156156b4577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe00183165b61ffff8216156156aa577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00183165b818416156156a0577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff80183165b600f821615615696577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc0183165b600382161561568a57837ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe6001920116915b16615661575b031660020b0160020b0260020b5b90614cd3565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01821661564d565b9060019060021c615647565b9060041c90615615565b9060081c906155e7565b9060101c906155ba565b9060201c9061558b565b9060401c9061555a565b60801c9150615525565b7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff27618955060ff809250031660020b0160020b0260020b61565b565b91955091999698929550969296606087015160a01b76ffffff0000000000000000000000000000000000000000167fffffffffffffffffff000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff60408a0151169216171782556fffffffffffffffffffffffffffffffff60a087015116809103615817575b50811561580857600260808601519101555b15146157eb576157d160406157c56020850151613431565b92015183519003613431565b6fffffffffffffffffffffffffffffffff169060801b1793565b6040015181516157fb9103613431565b6157d16020830151613431565b600160808601519101556157ad565b6fffffffffffffffffffffffffffffffff167fffffffffffffffffffffffffffffffff000000000000000000000000000000006003830154161760038201555f61579b565b5073ffffffffffffffffffffffffffffffffffffffff60408d01511673ffffffffffffffffffffffffffffffffffffffff60608701511614614b8d565b7f9e4d7cc7000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b827f7c9c6e8f000000000000000000000000000000000000000000000000000000005f5273ffffffffffffffffffffffffffffffffffffffff1660045260245260445ffd5b6060850173ffffffffffffffffffffffffffffffffffffffff8151168273ffffffffffffffffffffffffffffffffffffffff168111156158c457505173ffffffffffffffffffffffffffffffffffffffff1673fffd8963efd1fc6a506488495d951d5263988d268110156158995750614b2a565b9a509a50505050975050505050505f925f929190565b7f96206246000000000000000000000000000000000000000000000000000000005f5260045ffd5b50620f424062ffffff831614614ab4565b8061ffff881602620f424080820615159104019061ffff8816010390614a9f565b508360d01c62ffffff16614a94565b60028a015490614a6e565b5f610fff8860c41c1699614a35565b5f811215613296576393dafdf15f526004601cfd5b9173ffffffffffffffffffffffffffffffffffffffff821673ffffffffffffffffffffffffffffffffffffffff841611615ac8575b8215615abc5773ffffffffffffffffffffffffffffffffffffffff91615aaf917bffffffffffffffffffffffffffffffff00000000000000000000000084868185169403169160601b16615b65565b9116808206151591040190565b62bfc9215f526004601cfd5b919091615a60565b9073ffffffffffffffffffffffffffffffffffffffff811673ffffffffffffffffffffffffffffffffffffffff831611615b5f575b8115615abc57615b5773ffffffffffffffffffffffffffffffffffffffff91613296947bffffffffffffffffffffffffffffffff00000000000000000000000084868185169403169160601b166140f4565b911690614990565b90615b05565b929190615b738282866140f4565b93821561499a5709615b8157565b9060010190811561033057565b908215615bfd577bffffffffffffffffffffffffffffffff0000000000000000000000009060601b1673ffffffffffffffffffffffffffffffffffffffff82169283810292838311918404141615615bf0576132969261517792820391615b65565b63f5c787f15f526004601cfd5b50905090565b90918015615bfd5773ffffffffffffffffffffffffffffffffffffffff7bffffffffffffffffffffffffffffffff000000000000000000000000819460601b16921680820281615c538483614990565b14615c79575b5090615c68615c6d9284614990565b612eb5565b80820615159104011690565b8301838110615c59579150615c8d92615b65565b1690565b740100000000000000000000000000000000000000008110156130265773ffffffffffffffffffffffffffffffffffffffff169056fea264697066735822122001ea418b20f7cecdd2701d84e1f06f23225ed30746e37e25bf3cf7796e8dbed564736f6c634300081a0033
Loading...
Loading
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.