Verified contractExactMIT
PocketHook
Address0xdf81e1b059f43bf8e9d66670a1be1a8245bba0cc
- Balance
0.000929 ETH
- Transactions
1
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,329,231
- Creation transaction
- 0xef0b10747f…89c99304fc
5 files
- pocket/PocketHook.solmain9.84 KB
- pocket/PocketToken.sol2.13 KB
- pocket/v4/BitMath.sol2.61 KB
- pocket/v4/CustomRevert.sol5.17 KB
- pocket/v4/TickMath.sol12.38 KB
pocket/PocketHook.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
// Site: https://pocketv4.xyz X: https://x.com/pocketpad_io Token: PocketToken.sol Seeds: Pocket.sol
//
// POCKET. THE WATERING CAN.
//
// THE POOL One Uniswap v4 pool: native ETH (currency0) against $POCKET (currency1), LP fee 0, tick spacing
// 200, this hook. Only this hook can initialize it, only inside open(), only at OPEN_TICK.
// THE OPEN open() is the owner's, once. In one transaction it initializes the pool at tick 207200
// (about 1 ETH fully diluted) and puts the whole supply into one token-only band from tick
// -887200 up to the opening tick through the PositionManager, which mints the LP NFT to the owner.
// Rounding dust left in the hook is burnt.
// THE FEE 1% of the ETH side of every swap, in all four shapes. When ETH is the specified side (exact-in
// buys, exact-out sells) it is taken in beforeSwap; when it is the unspecified side (exact-out
// buys, exact-in sells) it is taken in afterSwap as a return delta. Half accrues to the owner,
// half to the Spirit Pot in Pocket.sol; both leave the hook by pull, never inside a swap.
// THE CAN A buy whose hookData is abi.encode(uint256[] ids), at most ten ids, waters those plants for the
// buyer (tx.origin) under Pocket's own rules; it never sows a seed. The watering runs in a try with a gas allowance, so a
// refused one (dead plant, not the holder, drought) never stops the buy. The hook first demands
// the allowance be present, so wallets that estimate gas include it rather than skipping the water.
// LIMITS When ETH is the specified side the fee is 1% of the amount asked for, even if a price limit fills
// the swap only in part. tx.origin is the buyer's own account only for plain wallets. A buy relayed by a smart account or a
// bundler waters nothing, and says so in the WaterSkipped event.
import {TickMath} from "./v4/TickMath.sol";
struct PoolKey {
address currency0;
address currency1;
uint24 fee;
int24 tickSpacing;
address hooks;
}
struct SwapParams {
bool zeroForOne;
int256 amountSpecified;
uint160 sqrtPriceLimitX96;
}
interface IPoolManager {
function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);
function take(address currency, address to, uint256 amount) external;
}
interface IPositionManager {
function modifyLiquidities(bytes calldata unlockData, uint256 deadline) external payable;
}
interface IPermit2 {
function approve(address token, address spender, uint160 amount, uint48 expiration) external;
}
interface IPocketSeeds {
function waterFrom(address actor, bytes calldata data) external;
}
import {PocketToken} from "./PocketToken.sol";
contract PocketHook {
int24 public constant TICK_SPACING = 200;
int24 public constant OPEN_TICK = 207200;
int24 public constant LOWER_TICK = -887200;
uint256 public constant FEE_DIVISOR = 100; // 1%
uint256 public constant MAX_WATER = 10;
uint256 public constant WATER_GAS_BASE = 60_000;
uint256 public constant WATER_GAS_PER_ID = 140_000; // a first watering on fresh ledger words, measured 132k
uint256 private constant FEE_SLOT = 0x706f636b65742e666565; // transient: the fee taken in beforeSwap
IPoolManager public immutable poolManager;
IPositionManager public immutable positionManager;
IPermit2 public immutable permit2;
IPocketSeeds public immutable pocket;
PocketToken public immutable token;
address public immutable owner;
uint160 public immutable openSqrtPrice;
bool public opened;
uint256 public ownerFees; // accrued, not yet withdrawn
uint256 public potPending; // accrued, not yet sent to the Spirit Pot
uint256 public feesTotal; // every fee wei ever taken
event Opened(uint256 liquidity, uint256 tokensInPool, uint256 dustBurnt);
event Fee(bool buy, uint256 eth, uint256 fee);
event WaterSkipped(address indexed buyer, bytes reason);
error NotPoolManager();
error NotOwner();
error AlreadyOpen();
error BadInit();
error NeedGasForWatering();
constructor(IPoolManager pm, IPositionManager posm, IPermit2 p2, IPocketSeeds seeds, address owner_) {
poolManager = pm;
positionManager = posm;
permit2 = p2;
pocket = seeds;
owner = owner_;
token = new PocketToken(address(this));
openSqrtPrice = TickMath.getSqrtPriceAtTick(OPEN_TICK);
}
receive() external payable {}
function poolKey() public view returns (PoolKey memory) {
return PoolKey(address(0), address(token), 0, TICK_SPACING, address(this));
}
// ---- the open ------------------------------------------------------------------------------------------
/// Initializes the pool and puts the whole supply in it; the LP NFT goes to the owner. Once, by the owner.
function open() external {
if (msg.sender != owner) revert NotOwner();
if (opened) revert AlreadyOpen();
opened = true;
PoolKey memory key = poolKey();
poolManager.initialize(key, openSqrtPrice);
uint256 amount = token.balanceOf(address(this));
uint256 lower = TickMath.getSqrtPriceAtTick(LOWER_TICK);
// token-only band below spot: liquidity from amount1, one unit short so the rounding-up never overdraws
uint256 liquidity = (amount << 96) / (uint256(openSqrtPrice) - lower) - 1;
token.approve(address(permit2), amount);
permit2.approve(address(token), address(positionManager), uint160(amount), uint48(block.timestamp));
bytes[] memory params = new bytes[](2);
params[0] = abi.encode(key, LOWER_TICK, OPEN_TICK, liquidity, uint128(0), uint128(amount), owner, bytes(""));
params[1] = abi.encode(address(0), address(token));
positionManager.modifyLiquidities(abi.encode(abi.encodePacked(uint8(0x02), uint8(0x0d)), params), block.timestamp);
uint256 dust = token.balanceOf(address(this));
if (dust != 0) token.burn(dust);
emit Opened(liquidity, amount - dust, dust);
}
// ---- the hook ------------------------------------------------------------------------------------------
function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external view returns (bytes4) {
if (msg.sender != address(poolManager)) revert NotPoolManager();
if (sender != address(this) || sqrtPriceX96 != openSqrtPrice || key.currency1 != address(token) || key.fee != 0) revert BadInit();
return this.beforeInitialize.selector;
}
function beforeSwap(address, PoolKey calldata, SwapParams calldata params, bytes calldata) external returns (bytes4, int256, uint24) {
if (msg.sender != address(poolManager)) revert NotPoolManager();
// ETH is the specified side on exact-in buys and exact-out sells
if (params.zeroForOne == (params.amountSpecified < 0)) {
uint256 amt = params.amountSpecified < 0 ? uint256(-params.amountSpecified) : uint256(params.amountSpecified);
uint256 fee = amt / FEE_DIVISOR;
assembly {
tstore(FEE_SLOT, fee)
}
return (this.beforeSwap.selector, int256(fee) << 128, 0);
}
return (this.beforeSwap.selector, 0, 0);
}
function afterSwap(address, PoolKey calldata, SwapParams calldata params, int256 delta, bytes calldata hookData) external returns (bytes4, int128) {
if (msg.sender != address(poolManager)) revert NotPoolManager();
uint256 fee;
int128 ret;
int128 eth = int128(delta >> 128);
if (params.zeroForOne == (params.amountSpecified < 0)) {
assembly {
fee := tload(FEE_SLOT)
tstore(FEE_SLOT, 0)
}
} else {
fee = uint256(uint128(eth < 0 ? -eth : eth)) / FEE_DIVISOR;
ret = int128(int256(fee));
}
if (fee != 0) {
poolManager.take(address(0), address(this), fee);
uint256 half = fee / 2;
potPending += half;
ownerFees += fee - half;
feesTotal += fee;
}
emit Fee(params.zeroForOne, uint256(uint128(eth < 0 ? -eth : eth)), fee);
if (params.zeroForOne && hookData.length >= 64) _water(hookData);
return (this.afterSwap.selector, ret);
}
function _water(bytes calldata hookData) private {
uint256 n = uint256(bytes32(hookData[32:64]));
if (n == 0 || n > MAX_WATER) {
emit WaterSkipped(tx.origin, "ids");
return;
}
uint256 allowance = WATER_GAS_BASE + WATER_GAS_PER_ID * n;
if (gasleft() < (allowance * 64) / 63 + 30_000) revert NeedGasForWatering();
try pocket.waterFrom{gas: allowance}(tx.origin, hookData) {} catch (bytes memory reason) {
emit WaterSkipped(tx.origin, reason);
}
}
// ---- the money -----------------------------------------------------------------------------------------
/// Sends the owner's accrued half to the owner. Anyone may call it.
function withdrawOwnerFees() external {
uint256 a = ownerFees;
ownerFees = 0;
(bool ok, ) = owner.call{value: a}("");
require(ok, "owner refused");
}
/// Sends the pot's accrued half to the Spirit Pot in Pocket.sol, with any ETH sent to the hook by mistake.
/// Anyone may call it.
function sendPot() external {
uint256 a = address(this).balance - ownerFees;
potPending = 0;
(bool ok, ) = address(pocket).call{value: a}("");
require(ok, "pot refused");
}
}
pocket/PocketToken.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
// Site: https://pocketv4.xyz X: https://x.com/pocketpad_io Pool: PocketHook.sol Seeds: Pocket.sol
//
// POCKET. THE COIN IN THE POCKET.
//
// $POCKET: 1,000,000,000 tokens, 18 decimals, minted once to the hook that deploys it, which puts all of them in
// the pool. No tax, no owner, no mint, no blacklist. Holders may burn their own.
contract PocketToken {
string public constant name = "Pocket";
string public constant symbol = "POCKET";
uint8 public constant decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor(address to) {
totalSupply = 1_000_000_000e18;
balanceOf[to] = totalSupply;
emit Transfer(address(0), to, totalSupply);
}
function approve(address spender, uint256 value) external returns (bool) {
allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transfer(address to, uint256 value) external returns (bool) {
_move(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint256 value) external returns (bool) {
uint256 a = allowance[from][msg.sender];
if (a != type(uint256).max) allowance[from][msg.sender] = a - value;
_move(from, to, value);
return true;
}
function burn(uint256 value) external {
balanceOf[msg.sender] -= value;
unchecked {
totalSupply -= value;
}
emit Transfer(msg.sender, address(0), value);
}
function _move(address from, address to, uint256 value) private {
require(to != address(0), "to zero");
balanceOf[from] -= value;
unchecked {
balanceOf[to] += value;
}
emit Transfer(from, to, value);
}
}
pocket/v4/BitMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
/// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol)
library BitMath {
/// @notice Returns the index of the most significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the most significant bit, must be greater than 0
/// @return r the index of the most significant bit
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020500060203020504000106050205030304010505030400000000))
}
}
/// @notice Returns the index of the least significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the least significant bit, must be greater than 0
/// @return r the index of the least significant bit
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
// Isolate the least significant bit.
x := and(x, sub(0, x))
// For the upper 3 bits of the result, use a De Bruijn-like lookup.
// Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
// forgefmt: disable-next-item
r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
0x8040405543005266443200005020610674053026020000107506200176117077)))
// For the lower 5 bits of the result, use a De Bruijn lookup.
// forgefmt: disable-next-item
r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
}
}
}
pocket/v4/CustomRevert.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
/// @dev Reverts with the selector of a custom error in the scratch space
function revertWith(bytes4 selector) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
revert(0, 0x04)
}
}
/// @dev Reverts with a custom error with an address argument in the scratch space
function revertWith(bytes4 selector, address addr) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with an int24 argument in the scratch space
function revertWith(bytes4 selector, int24 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, signextend(2, value))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with a uint160 argument in the scratch space
function revertWith(bytes4 selector, uint160 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with two int24 arguments
function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), signextend(2, value1))
mstore(add(fmp, 0x24), signextend(2, value2))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two uint160 arguments
function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two address arguments
function revertWith(bytes4 selector, address value1, address value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
/// @dev this method can be vulnerable to revert data bombs
function bubbleUpAndRevertWith(
address revertingContract,
bytes4 revertingFunctionSelector,
bytes4 additionalContext
) internal pure {
bytes4 wrappedErrorSelector = WrappedError.selector;
assembly ("memory-safe") {
// Ensure the size of the revert data is a multiple of 32 bytes
let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)
let fmp := mload(0x40)
// Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
mstore(fmp, wrappedErrorSelector)
mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(
add(fmp, 0x24),
and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
// offset revert reason
mstore(add(fmp, 0x44), 0x80)
// offset additional context
mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
// size revert reason
mstore(add(fmp, 0x84), returndatasize())
// revert reason
returndatacopy(add(fmp, 0xa4), 0, returndatasize())
// size additional context
mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
// additional context
mstore(
add(fmp, add(0xc4, encodedDataSize)),
and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
revert(fmp, add(0xe4, encodedDataSize))
}
}
}
pocket/v4/TickMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {BitMath} from "./BitMath.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
using CustomRevert for bytes4;
/// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK
error InvalidTick(int24 tick);
/// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK
error InvalidSqrtPrice(uint160 sqrtPriceX96);
/// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MAX_TICK = 887272;
/// @dev The minimum tick spacing value drawn from the range of type int16 that is greater than 0, i.e. min from the range [1, 32767]
int24 internal constant MIN_TICK_SPACING = 1;
/// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767]
int24 internal constant MAX_TICK_SPACING = type(int16).max;
/// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_PRICE = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
/// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1`
uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE =
1461446703485210103287273052203988822378723970342 - 4295128739 - 1;
/// @notice Given a tickSpacing, compute the maximum usable tick
function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MAX_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Given a tickSpacing, compute the minimum usable tick
function minUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MIN_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0)
/// at the given tick
function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
unchecked {
uint256 absTick;
assembly ("memory-safe") {
tick := signextend(2, tick)
// mask = 0 if tick >= 0 else -1 (all 1s)
let mask := sar(255, tick)
// if tick >= 0, |tick| = tick = 0 ^ tick
// if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)
// either way, |tick| = mask ^ (tick + mask)
absTick := xor(mask, add(mask, tick))
}
if (absTick > uint256(int256(MAX_TICK))) InvalidTick.selector.revertWith(tick);
// The tick is decomposed into bits, and for each bit with index i that is set, the product of 1/sqrt(1.0001^(2^i))
// is calculated (using Q128.128). The constants used for this calculation are rounded to the nearest integer
// Equivalent to:
// price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
// or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128
uint256 price;
assembly ("memory-safe") {
price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1)))
}
if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128;
assembly ("memory-safe") {
// if (tick > 0) price = type(uint256).max / price;
if sgt(tick, 0) { price := div(not(0), price) }
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtPrice of the output price is always consistent
// `sub(shl(32, 1), 1)` is `type(uint32).max`
// `price + type(uint32).max` will not overflow because `price` fits in 192 bits
sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1)))
}
}
}
/// @notice Calculates the greatest tick value such that getSqrtPriceAtTick(tick) <= sqrtPriceX96
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getSqrtPriceAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the getSqrtPriceAtTick(tick) is less than or equal to the input sqrtPriceX96
function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
unchecked {
// Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice();
// second inequality must be >= because the price can never reach the price at the max tick
// if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true
// if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1
if ((sqrtPriceX96 - MIN_SQRT_PRICE) > MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) {
InvalidSqrtPrice.selector.revertWith(sqrtPriceX96);
}
uint256 price = uint256(sqrtPriceX96) << 32;
uint256 r = price;
uint256 msb = BitMath.mostSignificantBit(r);
if (msb >= 128) r = price >> (msb - 127);
else r = price << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // Q22.128 number
// Magic number represents the ceiling of the maximum value of the error when approximating log_sqrt10001(x)
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
// Magic number represents the minimum value of the error when approximating log_sqrt10001(x), when
// sqrtPrice is from the range (2^-64, 2^64). This is safe as MIN_SQRT_PRICE is more than 2^-64. If MIN_SQRT_PRICE
// is changed, this may need to be changed too
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
}
Compiler settingsShow
{
"viaIR": true,
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.