forked from Uniswap/v4-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPool.sol
682 lines (597 loc) Β· 29.8 KB
/
Pool.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;
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} from "../types/BalanceDelta.sol";
library Pool {
using SafeCast for *;
using TickBitmap for mapping(int16 => uint256);
using Position for mapping(bytes32 => Position.Info);
using Position for Position.Info;
/// @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 initalize an already initialized pool
error PoolAlreadyInitialized();
/// @notice Thrown when trying to interact with a non-initialized pool
error PoolNotInitialized();
/// @notice Thrown when trying to swap amount of 0
error SwapAmountCannotBeZero();
/// @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();
/// The uint8 fees variables are represented as integer denominators (1/x)
/// For swap fees, the upper 4 bits are the fee for trading 1 for 0, and the lower 4 are for 0 for 1 and are taken as a percentage of the lp swap fee.
/// For withdraw fees the upper 4 bits are the fee on amount1, and the lower 4 are for amount0 and are taken as a percentage of the principle amount of the underlying position.
/// swapFee: 1->0 | 0->1
/// withdrawFee: fee1 | fee0
struct Slot0 {
// the current price
uint160 sqrtPriceX96;
// the current tick
int24 tick;
uint8 protocolSwapFee;
uint8 protocolWithdrawFee;
uint8 hookSwapFee;
uint8 hookWithdrawFee;
}
// 40 bits left!
// 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) revert TicksMisordered(tickLower, tickUpper);
if (tickLower < TickMath.MIN_TICK) revert TickLowerOutOfBounds(tickLower);
if (tickUpper > TickMath.MAX_TICK) revert TickUpperOutOfBounds(tickUpper);
}
function initialize(
State storage self,
uint160 sqrtPriceX96,
uint8 protocolSwapFee,
uint8 hookSwapFee,
uint8 protocolWithdrawFee,
uint8 hookWithdrawFee
) internal returns (int24 tick) {
if (self.slot0.sqrtPriceX96 != 0) revert PoolAlreadyInitialized();
tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96);
self.slot0 = Slot0({
sqrtPriceX96: sqrtPriceX96,
tick: tick,
protocolSwapFee: protocolSwapFee,
hookSwapFee: hookSwapFee,
protocolWithdrawFee: protocolWithdrawFee,
hookWithdrawFee: hookWithdrawFee
});
}
function setProtocolFees(State storage self, uint8 newProtocolSwapFee, uint8 newProtocolWithdrawFee) internal {
if (self.slot0.sqrtPriceX96 == 0) revert PoolNotInitialized();
self.slot0.protocolSwapFee = newProtocolSwapFee;
self.slot0.protocolWithdrawFee = newProtocolWithdrawFee;
}
function setHookFees(State storage self, uint8 newHookSwapFee, uint8 newHookWithdrawFee) internal {
if (self.slot0.sqrtPriceX96 == 0) revert PoolNotInitialized();
self.slot0.hookSwapFee = newHookSwapFee;
self.slot0.hookWithdrawFee = newHookWithdrawFee;
}
struct ModifyPositionParams {
// 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;
}
struct ModifyPositionState {
bool flippedLower;
uint128 liquidityGrossAfterLower;
bool flippedUpper;
uint128 liquidityGrossAfterUpper;
uint256 feeGrowthInside0X128;
uint256 feeGrowthInside1X128;
}
struct Fees {
uint256 feeForProtocol0;
uint256 feeForProtocol1;
uint256 feeForHook0;
uint256 feeForHook1;
}
/// @dev Effect changes to a position in a pool
/// @param params the position details and the change to the position's liquidity to effect
/// @return result the deltas of the token balances of the pool
function modifyPosition(State storage self, ModifyPositionParams memory params)
internal
returns (BalanceDelta result, Fees memory fees)
{
if (self.slot0.sqrtPriceX96 == 0) revert PoolNotInitialized();
checkTicks(params.tickLower, params.tickUpper);
uint256 feesOwed0;
uint256 feesOwed1;
{
ModifyPositionState memory state;
// if we need to update the ticks, do it
if (params.liquidityDelta != 0) {
(state.flippedLower, state.liquidityGrossAfterLower) =
updateTick(self, params.tickLower, params.liquidityDelta, false);
(state.flippedUpper, state.liquidityGrossAfterUpper) =
updateTick(self, params.tickUpper, params.liquidityDelta, true);
if (params.liquidityDelta > 0) {
uint128 maxLiquidityPerTick = tickSpacingToMaxLiquidityPerTick(params.tickSpacing);
if (state.liquidityGrossAfterLower > maxLiquidityPerTick) {
revert TickLiquidityOverflow(params.tickLower);
}
if (state.liquidityGrossAfterUpper > maxLiquidityPerTick) {
revert TickLiquidityOverflow(params.tickUpper);
}
}
if (state.flippedLower) {
self.tickBitmap.flipTick(params.tickLower, params.tickSpacing);
}
if (state.flippedUpper) {
self.tickBitmap.flipTick(params.tickUpper, params.tickSpacing);
}
}
(state.feeGrowthInside0X128, state.feeGrowthInside1X128) =
getFeeGrowthInside(self, params.tickLower, params.tickUpper);
(feesOwed0, feesOwed1) = self.positions.get(params.owner, params.tickLower, params.tickUpper).update(
params.liquidityDelta, state.feeGrowthInside0X128, state.feeGrowthInside1X128
);
// clear any tick data that is no longer needed
if (params.liquidityDelta < 0) {
if (state.flippedLower) {
clearTick(self, params.tickLower);
}
if (state.flippedUpper) {
clearTick(self, params.tickUpper);
}
}
}
if (params.liquidityDelta != 0) {
if (self.slot0.tick < params.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
result = result
+ toBalanceDelta(
SqrtPriceMath.getAmount0Delta(
TickMath.getSqrtRatioAtTick(params.tickLower),
TickMath.getSqrtRatioAtTick(params.tickUpper),
params.liquidityDelta
).toInt128(),
0
);
} else if (self.slot0.tick < params.tickUpper) {
result = result
+ toBalanceDelta(
SqrtPriceMath.getAmount0Delta(
self.slot0.sqrtPriceX96, TickMath.getSqrtRatioAtTick(params.tickUpper), params.liquidityDelta
).toInt128(),
SqrtPriceMath.getAmount1Delta(
TickMath.getSqrtRatioAtTick(params.tickLower), self.slot0.sqrtPriceX96, params.liquidityDelta
).toInt128()
);
self.liquidity = params.liquidityDelta < 0
? self.liquidity - uint128(-params.liquidityDelta)
: self.liquidity + uint128(params.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
result = result
+ toBalanceDelta(
0,
SqrtPriceMath.getAmount1Delta(
TickMath.getSqrtRatioAtTick(params.tickLower),
TickMath.getSqrtRatioAtTick(params.tickUpper),
params.liquidityDelta
).toInt128()
);
}
}
if (params.liquidityDelta < 0 && self.slot0.hookWithdrawFee > 0) {
// Only take fees if the hook withdraw fee is set and the liquidity is being removed.
fees = _calculateExternalFees(self, result);
// Amounts are balances owed to the pool. When negative, they represent the balance a user can take.
// Since protocol and hook fees are extracted on the balance a user can take
// they are owed (added) back to the pool where they are kept to be collected by the fee recipients.
result = result
+ toBalanceDelta(
fees.feeForHook0.toInt128() + fees.feeForProtocol0.toInt128(),
fees.feeForHook1.toInt128() + fees.feeForProtocol1.toInt128()
);
}
// Fees earned from LPing are removed from the pool balance.
result = result - toBalanceDelta(feesOwed0.toInt128(), feesOwed1.toInt128());
}
function _calculateExternalFees(State storage self, BalanceDelta result) internal view returns (Fees memory fees) {
int128 amount0 = result.amount0();
int128 amount1 = result.amount1();
uint8 hookFee0 = self.slot0.hookWithdrawFee % 16;
uint8 hookFee1 = self.slot0.hookWithdrawFee >> 4;
uint8 protocolFee0 = self.slot0.protocolWithdrawFee % 16;
uint8 protocolFee1 = self.slot0.protocolWithdrawFee >> 4;
if (amount0 < 0 && hookFee0 > 0) {
fees.feeForHook0 = uint128(-amount0) / hookFee0;
}
if (amount1 < 0 && hookFee1 > 0) {
fees.feeForHook1 = uint128(-amount1) / hookFee1;
}
// A protocol fee is only applied if the hook fee is applied.
if (protocolFee0 > 0 && fees.feeForHook0 > 0) {
fees.feeForProtocol0 = fees.feeForHook0 / protocolFee0;
fees.feeForHook0 -= fees.feeForProtocol0;
}
if (protocolFee1 > 0 && fees.feeForHook1 > 0) {
fees.feeForProtocol1 = fees.feeForHook1 / protocolFee1;
fees.feeForHook1 -= fees.feeForProtocol1;
}
return fees;
}
struct SwapCache {
// liquidity at the beginning of the swap
uint128 liquidityStart;
// the protocol fee for the input token
uint8 protocolFee;
// the hook fee for the input token
uint8 hookFee;
}
// 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 {
uint24 fee;
int24 tickSpacing;
bool zeroForOne;
int256 amountSpecified;
uint160 sqrtPriceLimitX96;
}
/// @dev Executes a swap against the state, and returns the amount deltas of the pool
function swap(State storage self, SwapParams memory params)
internal
returns (BalanceDelta result, uint256 feeForProtocol, uint256 feeForHook, SwapState memory state)
{
if (params.amountSpecified == 0) revert SwapAmountCannotBeZero();
Slot0 memory slot0Start = self.slot0;
if (self.slot0.sqrtPriceX96 == 0) revert PoolNotInitialized();
if (params.zeroForOne) {
if (params.sqrtPriceLimitX96 >= slot0Start.sqrtPriceX96) {
revert PriceLimitAlreadyExceeded(slot0Start.sqrtPriceX96, params.sqrtPriceLimitX96);
}
if (params.sqrtPriceLimitX96 <= TickMath.MIN_SQRT_RATIO) {
revert PriceLimitOutOfBounds(params.sqrtPriceLimitX96);
}
} else {
if (params.sqrtPriceLimitX96 <= slot0Start.sqrtPriceX96) {
revert PriceLimitAlreadyExceeded(slot0Start.sqrtPriceX96, params.sqrtPriceLimitX96);
}
if (params.sqrtPriceLimitX96 >= TickMath.MAX_SQRT_RATIO) {
revert PriceLimitOutOfBounds(params.sqrtPriceLimitX96);
}
}
SwapCache memory cache = SwapCache({
liquidityStart: self.liquidity,
protocolFee: params.zeroForOne ? (slot0Start.protocolSwapFee % 16) : (slot0Start.protocolSwapFee >> 4),
hookFee: params.zeroForOne ? (slot0Start.hookSwapFee % 16) : (slot0Start.hookSwapFee >> 4)
});
bool exactInput = params.amountSpecified > 0;
state = SwapState({
amountSpecifiedRemaining: params.amountSpecified,
amountCalculated: 0,
sqrtPriceX96: slot0Start.sqrtPriceX96,
tick: slot0Start.tick,
feeGrowthGlobalX128: params.zeroForOne ? self.feeGrowthGlobal0X128 : self.feeGrowthGlobal1X128,
liquidity: cache.liquidityStart
});
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, params.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;
} else if (step.tickNext > TickMath.MAX_TICK) {
step.tickNext = TickMath.MAX_TICK;
}
// get the price for the next tick
step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(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,
(
params.zeroForOne
? step.sqrtPriceNextX96 < params.sqrtPriceLimitX96
: step.sqrtPriceNextX96 > params.sqrtPriceLimitX96
) ? params.sqrtPriceLimitX96 : step.sqrtPriceNextX96,
state.liquidity,
state.amountSpecifiedRemaining,
params.fee
);
if (exactInput) {
// 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();
} else {
unchecked {
state.amountSpecifiedRemaining += step.amountOut.toInt256();
}
state.amountCalculated = state.amountCalculated + (step.amountIn + step.feeAmount).toInt256();
}
// if the protocol fee is on, calculate how much is owed, decrement feeAmount, and increment protocolFee
if (cache.protocolFee > 0) {
// A: calculate the amount of the fee that should go to the protocol
uint256 delta = step.feeAmount / cache.protocolFee;
// A: subtract it from the regular fee and add it to the protocol fee
unchecked {
step.feeAmount -= delta;
feeForProtocol += delta;
}
}
if (cache.hookFee > 0) {
// step.feeAmount has already been updated to account for the protocol fee
uint256 delta = step.feeAmount / cache.hookFee;
unchecked {
step.feeAmount -= delta;
feeForHook += 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) {
int128 liquidityNet = Pool.crossTick(
self,
step.tickNext,
(params.zeroForOne ? state.feeGrowthGlobalX128 : self.feeGrowthGlobal0X128),
(params.zeroForOne ? self.feeGrowthGlobal1X128 : state.feeGrowthGlobalX128)
);
// if we're moving leftward, we interpret liquidityNet as the opposite sign
// safe because liquidityNet cannot be type(int128).min
unchecked {
if (params.zeroForOne) liquidityNet = -liquidityNet;
}
state.liquidity = liquidityNet < 0
? state.liquidity - uint128(-liquidityNet)
: state.liquidity + uint128(liquidityNet);
}
unchecked {
state.tick = params.zeroForOne ? step.tickNext - 1 : step.tickNext;
}
} 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.getTickAtSqrtRatio(state.sqrtPriceX96);
}
}
(self.slot0.sqrtPriceX96, self.slot0.tick) = (state.sqrtPriceX96, state.tick);
// update liquidity if it changed
if (cache.liquidityStart != state.liquidity) self.liquidity = state.liquidity;
// update fee growth global
if (params.zeroForOne) {
self.feeGrowthGlobal0X128 = state.feeGrowthGlobalX128;
} else {
self.feeGrowthGlobal1X128 = state.feeGrowthGlobalX128;
}
unchecked {
if (params.zeroForOne == exactInput) {
result = toBalanceDelta(
(params.amountSpecified - state.amountSpecifiedRemaining).toInt128(),
state.amountCalculated.toInt128()
);
} else {
result = toBalanceDelta(
state.amountCalculated.toInt128(),
(params.amountSpecified - state.amountSpecifiedRemaining).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) {
if (state.liquidity == 0) revert NoLiquidityToReceiveFees();
delta = toBalanceDelta(amount0.toInt128(), amount1.toInt128());
unchecked {
if (amount0 > 0) {
state.feeGrowthGlobal0X128 += FullMath.mulDiv(amount0, FixedPoint128.Q128, state.liquidity);
}
if (amount1 > 0) {
state.feeGrowthGlobal1X128 += FullMath.mulDiv(amount1, FixedPoint128.Q128, state.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))
// shift right 128 bits to get just liquidityNet
liquidityNetBefore := shr(128, liquidity)
}
liquidityGrossAfter = liquidityDelta < 0
? liquidityGrossBefore - uint128(-liquidityDelta)
: liquidityGrossBefore + uint128(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 The max liquidity per tick
function tickSpacingToMaxLiquidityPerTick(int24 tickSpacing) internal pure returns (uint128) {
unchecked {
return uint128(
(type(uint128).max * uint256(int256(tickSpacing)))
/ uint256(int256(TickMath.MAX_TICK * 2 + tickSpacing))
);
}
}
/// @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;
}
}
}