Skip to content

Reading Elysium

Mine

LpLocker.sol

153 lines · sha256 9e7167e71dabd8d3a4a5ee084b1f70c13012737828ff58d387029ac9f9c29a34 · Raw

1// SPDX-License-Identifier: MIT
2pragma solidity ^0.8.26;
3
4import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
5import {IUnlockCallback} from "@uniswap/v4-core/src/interfaces/callback/IUnlockCallback.sol";
6import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
7import {PoolId, PoolIdLibrary} from "@uniswap/v4-core/src/types/PoolId.sol";
8import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
9import {ModifyLiquidityParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";
10import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol";
11import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
12import {SqrtPriceMath} from "@uniswap/v4-core/src/libraries/SqrtPriceMath.sol";
13import {Position} from "@uniswap/v4-core/src/libraries/Position.sol";
14import {LiquidityAmounts} from "@uniswap/v4-periphery/src/libraries/LiquidityAmounts.sol";
15import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
16import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
17import {KibblePool} from "./libraries/KibblePool.sol";
18
19/// @title LpLocker
20/// @notice Owns every HYPE / KIBBLE liquidity position of the protocol, forever (docs §3, §6, §9, §11).
21/// @dev Positions are owned directly in the v4 PoolManager by this contract (owner = address(this),
22/// full range, salt = bytes32(index)). This contract can only ADD liquidity: it never calls
23/// modifyLiquidity with a negative delta, has no withdraw, no transfer, no owner and no collect.
24/// Each add uses a fresh salt so no existing position is ever touched again: in v4, touching a position
25/// settles its accrued fees to the owner, so with fresh salts swap fees accrued by locked positions are never
26/// collected and stay in the PoolManager forever.
27contract LpLocker is IUnlockCallback {
28 using SafeERC20 for IERC20;
29 using PoolIdLibrary for PoolKey;
30 using StateLibrary for IPoolManager;
31
32 error NotPoolManager();
33 error RefundFailed();
34
35 /// @notice Not a docs event: emitted on every locked add so the LP history can be indexed.
36 event LiquidityLocked(uint256 indexed index, uint128 liquidity, uint256 hypeAmount, uint256 kibbleAmount);
37
38 IPoolManager public immutable poolManager;
39 address public immutable kibble;
40 PoolId public immutable poolId;
41
42 /// @notice Number of locked positions (position i has salt bytes32(i)).
43 uint256 public positionCount;
44 /// @notice Sum of the liquidity of all locked positions. Never decreases.
45 uint256 public totalLiquidity;
46 /// @notice Cumulative HYPE deposited into locked positions.
47 uint256 public lockedHype;
48 /// @notice Cumulative KIBBLE deposited into locked positions.
49 uint256 public lockedKibble;
50 /// @notice Liquidity of position i at creation.
51 mapping(uint256 => uint128) public positionLiquidity;
52
53 constructor(IPoolManager poolManager_, address kibble_) {
54 poolManager = poolManager_;
55 kibble = kibble_;
56 poolId = KibblePool.key(kibble_).toId();
57 }
58
59 /// @notice Adds full-range liquidity with `msg.value` HYPE and up to `kibbleAmount` KIBBLE (pulled from the
60 /// caller, approval needed) and locks it forever. Unused HYPE / KIBBLE is refunded to the caller.
61 /// Called by `Genesis` at block 0 and by `Zapper` on every rig purchase after block 0. Anyone may call:
62 /// adding is a donation to locked liquidity.
63 function addLiquidity(uint256 kibbleAmount)
64 external
65 payable
66 returns (uint128 liquidity, uint256 hypeUsed, uint256 kibbleUsed)
67 {
68 if (kibbleAmount > 0) IERC20(kibble).safeTransferFrom(msg.sender, address(this), kibbleAmount);
69
70 (uint160 sqrtP,,,) = poolManager.getSlot0(poolId);
71 if (sqrtP != 0 && msg.value > 1 && kibbleAmount > 1) {
72 // 1 wei margin on each side absorbs v4's round-up when converting liquidity back to amounts.
73 liquidity = LiquidityAmounts.getLiquidityForAmounts(
74 sqrtP,
75 TickMath.getSqrtPriceAtTick(KibblePool.tickLower()),
76 TickMath.getSqrtPriceAtTick(KibblePool.tickUpper()),
77 msg.value - 1,
78 kibbleAmount - 1
79 );
80 }
81 if (liquidity > 0) {
82 uint256 index = positionCount;
83 (hypeUsed, kibbleUsed) = abi.decode(poolManager.unlock(abi.encode(index, liquidity)), (uint256, uint256));
84 positionCount = index + 1;
85 positionLiquidity[index] = liquidity;
86 totalLiquidity += liquidity;
87 lockedHype += hypeUsed;
88 lockedKibble += kibbleUsed;
89 emit LiquidityLocked(index, liquidity, hypeUsed, kibbleUsed);
90 }
91
92 uint256 hypeBack = msg.value - hypeUsed;
93 uint256 kibbleBack = kibbleAmount - kibbleUsed;
94 if (kibbleBack > 0) IERC20(kibble).safeTransfer(msg.sender, kibbleBack);
95 if (hypeBack > 0) {
96 (bool ok,) = msg.sender.call{value: hypeBack}("");
97 if (!ok) revert RefundFailed();
98 }
99 }
100
101 /// @inheritdoc IUnlockCallback
102 function unlockCallback(bytes calldata data) external returns (bytes memory) {
103 if (msg.sender != address(poolManager)) revert NotPoolManager();
104 (uint256 index, uint128 liquidity) = abi.decode(data, (uint256, uint128));
105 PoolKey memory key = KibblePool.key(kibble);
106 (BalanceDelta delta,) = poolManager.modifyLiquidity(
107 key,
108 ModifyLiquidityParams({
109 tickLower: KibblePool.tickLower(),
110 tickUpper: KibblePool.tickUpper(),
111 liquidityDelta: int256(uint256(liquidity)),
112 salt: bytes32(index)
113 }),
114 ""
115 );
116 uint256 hypeOwed = uint256(uint128(-delta.amount0()));
117 uint256 kibbleOwed = uint256(uint128(-delta.amount1()));
118 if (hypeOwed > 0) poolManager.settle{value: hypeOwed}();
119 if (kibbleOwed > 0) {
120 poolManager.sync(key.currency1);
121 IERC20(kibble).safeTransfer(address(poolManager), kibbleOwed);
122 poolManager.settle();
123 }
124 return abi.encode(hypeOwed, kibbleOwed);
125 }
126
127 // ------------------------------------------------------------------ views (docs §14 "LP locked")
128
129 /// @notice Liquidity of locked position i as stored in the PoolManager (proves it is still there).
130 function onchainPositionLiquidity(uint256 i) public view returns (uint128) {
131 bytes32 key =
132 Position.calculatePositionKey(address(this), KibblePool.tickLower(), KibblePool.tickUpper(), bytes32(i));
133 return poolManager.getPositionLiquidity(poolId, key);
134 }
135
136 /// @notice HYPE and KIBBLE currently represented by all locked positions at the current pool price
137 /// (principal only, fees excluded).
138 function lockedAmounts() external view returns (uint256 hype, uint256 kibbleAmt) {
139 (uint160 sqrtP,,,) = poolManager.getSlot0(poolId);
140 uint256 l = totalLiquidity;
141 if (sqrtP == 0 || l == 0) return (0, 0);
142 uint160 sqrtUpper = TickMath.getSqrtPriceAtTick(KibblePool.tickUpper());
143 uint160 sqrtLower = TickMath.getSqrtPriceAtTick(KibblePool.tickLower());
144 hype = SqrtPriceMath.getAmount0Delta(sqrtP, sqrtUpper, uint128(l), false);
145 kibbleAmt = SqrtPriceMath.getAmount1Delta(sqrtLower, sqrtP, uint128(l), false);
146 }
147
148 /// @notice Pool key of the locked liquidity.
149 function poolKey() external view returns (PoolKey memory) {
150 return KibblePool.key(kibble);
151 }
152}
153