-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathUniswapV4Lib.sol
More file actions
546 lines (460 loc) · 19.8 KB
/
Copy pathUniswapV4Lib.sol
File metadata and controls
546 lines (460 loc) · 19.8 KB
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
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.21;
import { Currency } from "../../lib/uniswap-v4-core/src/types/Currency.sol";
import { PoolKey } from "../../lib/uniswap-v4-core/src/types/PoolKey.sol";
import { IV4Router } from "../../lib/uniswap-v4-periphery/src/interfaces/IV4Router.sol";
import { Actions } from "../../lib/uniswap-v4-periphery/src/libraries/Actions.sol";
import { PositionInfo } from "../../lib/uniswap-v4-periphery/src/libraries/PositionInfoLibrary.sol";
import { IERC20Like, IPermit2Like } from "../interfaces/Common.sol";
import { IALMProxy } from "../interfaces/IALMProxy.sol";
import { IRateLimits } from "../interfaces/IRateLimits.sol";
import { IPositionManagerLike, IUniversalRouterLike } from "../interfaces/UniswapV4.sol";
import { RateLimitHelpers } from "../RateLimitHelpers.sol";
library UniswapV4Lib {
struct TickLimits {
int24 tickLowerMin;
int24 tickUpperMax;
uint24 maxTickSpacing;
}
bytes32 public constant LIMIT_DEPOSIT = keccak256("LIMIT_UNISWAP_V4_DEPOSIT");
bytes32 public constant LIMIT_WITHDRAW = keccak256("LIMIT_UNISWAP_V4_WITHDRAW");
bytes32 public constant LIMIT_SWAP = keccak256("LIMIT_UNISWAP_V4_SWAP");
uint256 internal constant _V4_SWAP = 0x10;
// NOTE: From https://docs.uniswap.org/contracts/v4/deployments (Ethereum Mainnet).
address internal constant _PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
address internal constant _POSITION_MANAGER = 0xbD216513d74C8cf14cf4747E6AaA6420FF64ee9e;
address internal constant _ROUTER = 0x66a9893cC07D91D95644AEDD05D03f95e1dBA8Af;
/**********************************************************************************************/
/*** Interactive Functions ***/
/**********************************************************************************************/
function mintPosition(
address proxy,
address rateLimits,
bytes32 poolId,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint128 amount0Max,
uint128 amount1Max,
mapping(bytes32 poolId => TickLimits tickLimits) storage tickLimits
)
external
{
_checkTickLimits(tickLimits[poolId], tickLower, tickUpper);
PoolKey memory poolKey = _getPoolKeyFromPoolId(poolId);
_requirePoolIdMatch(poolId, poolKey);
bytes memory callData = _getMintCalldata({
poolKey : poolKey,
tickLower : tickLower,
tickUpper : tickUpper,
liquidity : liquidity,
amount0Max : amount0Max,
amount1Max : amount1Max,
proxy : proxy
});
_increaseLiquidity({
proxy : proxy,
rateLimits : rateLimits,
poolId : poolId,
token0 : Currency.unwrap(poolKey.currency0),
token1 : Currency.unwrap(poolKey.currency1),
amount0Max : amount0Max,
amount1Max : amount1Max,
callData : callData
});
}
function increasePosition(
address proxy,
address rateLimits,
bytes32 poolId,
uint256 tokenId,
uint128 liquidityIncrease,
uint128 amount0Max,
uint128 amount1Max,
mapping(bytes32 poolId => TickLimits tickLimits) storage tickLimits
)
external
{
// Must not increase liquidity on a position that is not owned by the ALMProxy.
require(
IPositionManagerLike(_POSITION_MANAGER).ownerOf(tokenId) == proxy,
"MC/non-proxy-position"
);
( PoolKey memory poolKey, PositionInfo info ) = _getPoolKeyAndPositionInfo(tokenId);
_requirePoolIdMatch(poolId, poolKey);
// Since funds are being added to the position, the ticks of the position need to be checked
// against the current constraints, since it's possible the position was minted under
// outdated tick limits, or was transferred to the proxy.
_checkTickLimits(tickLimits[poolId], info.tickLower(), info.tickUpper());
bytes memory callData = _getIncreaseLiquidityCallData({
poolKey : poolKey,
tokenId : tokenId,
liquidityIncrease : liquidityIncrease,
amount0Max : amount0Max,
amount1Max : amount1Max
});
_increaseLiquidity({
proxy : proxy,
rateLimits : rateLimits,
poolId : poolId,
token0 : Currency.unwrap(poolKey.currency0),
token1 : Currency.unwrap(poolKey.currency1),
amount0Max : amount0Max,
amount1Max : amount1Max,
callData : callData
});
}
function decreasePosition(
address proxy,
address rateLimits,
bytes32 poolId,
uint256 tokenId,
uint128 liquidityDecrease,
uint128 amount0Min,
uint128 amount1Min
)
external
{
PoolKey memory poolKey = _getPoolKeyFromTokenId(tokenId);
// NOTE: No need to check the token ownership here, as the proxy will be defined as the
// recipient of the tokens, so the worst case is that another account's position is
// decreased or closed by the proxy.
_requirePoolIdMatch(poolId, poolKey);
bytes memory callData = _getDecreaseLiquidityCallData({
proxy : proxy,
poolKey : poolKey,
tokenId : tokenId,
liquidityDecrease : liquidityDecrease,
amount0Min : amount0Min,
amount1Min : amount1Min
});
_decreaseLiquidity({
proxy : proxy,
rateLimits : rateLimits,
poolId : poolId,
token0 : Currency.unwrap(poolKey.currency0),
token1 : Currency.unwrap(poolKey.currency1),
callData : callData
});
}
function swap(
address proxy,
address rateLimits,
bytes32 poolId,
address tokenIn,
uint128 amountIn,
uint128 amountOutMin,
uint256 maxSlippage
)
external
{
require(maxSlippage != 0, "MC/max-slippage-not-set");
PoolKey memory poolKey = _getPoolKeyFromPoolId(poolId);
_requirePoolIdMatch(poolId, poolKey);
require(
tokenIn == Currency.unwrap(poolKey.currency0) ||
tokenIn == Currency.unwrap(poolKey.currency1),
"MC/invalid-tokenIn"
);
// Perform rate limit decrease.
// NOTE: Rate limit decrease does not account for the net amount of tokenIn actually taken.
IRateLimits(rateLimits).triggerRateLimitDecrease(
RateLimitHelpers.makeBytes32Key(LIMIT_SWAP, poolId),
_getNormalizedBalance(tokenIn, amountIn)
);
bytes memory actions = abi.encodePacked(
uint8(Actions.SWAP_EXACT_IN_SINGLE),
uint8(Actions.SETTLE_ALL),
uint8(Actions.TAKE_ALL)
);
bool zeroForOne = tokenIn == Currency.unwrap(poolKey.currency0);
address tokenOut = zeroForOne
? Currency.unwrap(poolKey.currency1)
: Currency.unwrap(poolKey.currency0);
require(
_getNormalizedBalance(tokenOut, amountOutMin) * 1e18 >=
_getNormalizedBalance(tokenIn, amountIn) * maxSlippage,
"MC/amountOutMin-too-low"
);
bytes[] memory params = new bytes[](3);
params[0] = abi.encode(
IV4Router.ExactInputSingleParams({
poolKey : poolKey,
zeroForOne : zeroForOne,
amountIn : amountIn,
amountOutMinimum : amountOutMin,
hookData : bytes("")
})
);
params[1] = abi.encode(tokenIn, amountIn);
params[2] = abi.encode(tokenOut, amountOutMin);
// Combine actions and params into inputs.
bytes[] memory inputs = new bytes[](1);
inputs[0] = abi.encode(actions, params);
_approveWithPermit2(proxy, tokenIn, _ROUTER, amountIn);
// Perform action.
IALMProxy(proxy).doCall(
_ROUTER,
abi.encodeCall(
IUniversalRouterLike.execute,
(abi.encodePacked(uint8(_V4_SWAP)), inputs, block.timestamp)
)
);
// Reset approval of Permit2 in tokenIn.
_approveWithPermit2(proxy, tokenIn, _ROUTER, 0);
}
/**********************************************************************************************/
/*** Internal Interactive Functions ***/
/**********************************************************************************************/
function _approveWithPermit2(
address proxy,
address token,
address spender,
uint128 amount
)
internal
{
// Approve the Permit2 contract to spend none of the token (success is optional).
// NOTE: We don't care about the success of this call, since the only outcomes are:
// - the allowance is 0 (it was reset or was already 0)
// - the allowance is not 0, in which case the success of the overall set of
// operations is dependent on the success of the subsequent calls.
// In other words, this is a convenience call that may not even be needed for success.
proxy.call(
abi.encodeCall(
IALMProxy.doCall,
(token, abi.encodeCall(IERC20Like.approve, (_PERMIT2, 0)))
)
);
if (amount != 0) {
// Approve the Permit2 contract to spend the amount of token (success is mandatory).
bytes memory approveResult = IALMProxy(proxy).doCall(
token,
abi.encodeCall(IERC20Like.approve, (_PERMIT2, amount))
);
// Revert if approve returns anything, and that anything is not `true`.
require(
approveResult.length == 0 || abi.decode(approveResult, (bool)),
"MC/permit2-approve-failed"
);
}
// Finally, approve the spender to spend the token via Permit2.
IALMProxy(proxy).doCall(
_PERMIT2,
abi.encodeCall(
IPermit2Like.approve,
(token, spender, uint160(amount), uint48(block.timestamp))
)
);
}
function _increaseLiquidity(
address proxy,
address rateLimits,
bytes32 poolId,
address token0,
address token1,
uint128 amount0Max,
uint128 amount1Max,
bytes memory callData
)
internal
{
_approveWithPermit2(proxy, token0, _POSITION_MANAGER, amount0Max);
_approveWithPermit2(proxy, token1, _POSITION_MANAGER, amount1Max);
// Get token balances before liquidity increase.
uint256 startingBalance0 = _getBalance(token0, proxy);
uint256 startingBalance1 = _getBalance(token1, proxy);
// Perform action
IALMProxy(proxy).doCall(_POSITION_MANAGER, callData);
// Get token balances after liquidity increase.
uint256 endingBalance0 = _getBalance(token0, proxy);
uint256 endingBalance1 = _getBalance(token1, proxy);
// Account for the theoretical possibility of receiving tokens when adding liquidity by
// using a clamped subtraction.
// NOTE: The limitation of this integration is the assumption that the tokens are valued
// equally (i.e. 1.000000 USDC = 1.000000000000000000 USDS).
uint256 rateLimitDecrease = _clampedSub(
_getNormalizedBalance(token0, startingBalance0) +
_getNormalizedBalance(token1, startingBalance1),
_getNormalizedBalance(token0, endingBalance0) +
_getNormalizedBalance(token1, endingBalance1)
);
// Perform rate limit decrease.
// NOTE: Rate limit decrease is net of any token0 or token1 received due to fees.
IRateLimits(rateLimits).triggerRateLimitDecrease(
RateLimitHelpers.makeBytes32Key(LIMIT_DEPOSIT, poolId),
rateLimitDecrease
);
// Reset approvals for token0 and token1.
_approveWithPermit2(proxy, token0, _POSITION_MANAGER, 0);
_approveWithPermit2(proxy, token1, _POSITION_MANAGER, 0);
}
function _decreaseLiquidity(
address proxy,
address rateLimits,
bytes32 poolId,
address token0,
address token1,
bytes memory callData
)
internal
{
// Get token balances before liquidity decrease.
uint256 startingBalance0 = _getBalance(token0, proxy);
uint256 startingBalance1 = _getBalance(token1, proxy);
// Perform action.
IALMProxy(proxy).doCall(_POSITION_MANAGER, callData);
// Get token balances after liquidity decrease.
uint256 endingBalance0 = _getBalance(token0, proxy);
uint256 endingBalance1 = _getBalance(token1, proxy);
// NOTE: The limitation of this integration is the assumption that the tokens are valued
// equally (i.e. 1.000000 USDC = 1.000000000000000000 USDS).
uint256 rateLimitDecrease =
_getNormalizedBalance(token0, endingBalance0 - startingBalance0) +
_getNormalizedBalance(token1, endingBalance1 - startingBalance1);
// Perform rate limit decrease.
// NOTE: Rate limit decrease includes any token0 or token1 received due to fees.
IRateLimits(rateLimits).triggerRateLimitDecrease(
RateLimitHelpers.makeBytes32Key(LIMIT_WITHDRAW, poolId),
rateLimitDecrease
);
}
/**********************************************************************************************/
/*** Internal View/Pure Functions ***/
/**********************************************************************************************/
function _checkTickLimits(TickLimits memory limits, int24 tickLower, int24 tickUpper)
internal pure
{
require(limits.maxTickSpacing != 0, "MC/tickLimits-not-set");
require(tickLower < tickUpper, "MC/ticks-misordered");
require(tickLower >= limits.tickLowerMin, "MC/tickLower-too-low");
require(tickUpper <= limits.tickUpperMax, "MC/tickUpper-too-high");
require(
uint256(int256(tickUpper) - int256(tickLower)) <= limits.maxTickSpacing,
"MC/tickSpacing-too-wide"
);
}
function _clampedSub(uint256 a, uint256 b) internal pure returns (uint256 c) {
return a > b ? a - b : 0;
}
function _getBalance(address token, address account) internal view returns (uint256 balance) {
return IERC20Like(token).balanceOf(account);
}
function _getMintCalldata(
address proxy,
PoolKey memory poolKey,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint128 amount0Max,
uint128 amount1Max
)
internal view returns (bytes memory callData)
{
bytes memory actions = abi.encodePacked(
uint8(Actions.MINT_POSITION),
uint8(Actions.SETTLE_PAIR)
);
bytes[] memory params = new bytes[](2);
params[0] = abi.encode(
poolKey, // Which pool to mint in
tickLower, // Position's lower price bound
tickUpper, // Position's upper price bound
uint256(liquidity), // Amount of liquidity to mint
amount0Max, // Maximum amount of token0 to use
amount1Max, // Maximum amount of token1 to use
proxy, // NFT recipient
"" // No hook data needed
);
params[1] = abi.encode(
poolKey.currency0, // First token to settle
poolKey.currency1 // Second token to settle
);
return _getModifyLiquiditiesCallData(actions, params);
}
function _getIncreaseLiquidityCallData(
PoolKey memory poolKey,
uint256 tokenId,
uint128 liquidityIncrease,
uint128 amount0Max,
uint128 amount1Max
)
internal view returns (bytes memory callData)
{
bytes memory actions = abi.encodePacked(
uint8(Actions.INCREASE_LIQUIDITY),
uint8(Actions.SETTLE_PAIR)
);
bytes[] memory params = new bytes[](2);
params[0] = abi.encode(
tokenId, // Position to increase
uint256(liquidityIncrease), // Amount to add
amount0Max, // Maximum token0 to spend
amount1Max, // Maximum token1 to spend
"" // No hook data needed
);
params[1] = abi.encode(
poolKey.currency0, // First token to settle
poolKey.currency1 // Second token to settle
);
return _getModifyLiquiditiesCallData(actions, params);
}
function _getDecreaseLiquidityCallData(
address proxy,
PoolKey memory poolKey,
uint256 tokenId,
uint128 liquidityDecrease,
uint128 amount0Min,
uint128 amount1Min
)
internal view returns (bytes memory callData)
{
bytes memory actions = abi.encodePacked(
uint8(Actions.DECREASE_LIQUIDITY),
uint8(Actions.TAKE_PAIR)
);
bytes[] memory params = new bytes[](2);
params[0] = abi.encode(
tokenId, // Position to decrease
uint256(liquidityDecrease), // Amount to remove
amount0Min, // Minimum token0 to receive
amount1Min, // Minimum token1 to receive
"" // No hook data needed
);
params[1] = abi.encode(
poolKey.currency0, // First token
poolKey.currency1, // Second token
proxy // Who receives the tokens
);
return _getModifyLiquiditiesCallData(actions, params);
}
function _getModifyLiquiditiesCallData(bytes memory actions, bytes[] memory params)
internal view returns (bytes memory callData)
{
return abi.encodeCall(
IPositionManagerLike.modifyLiquidities,
(abi.encode(actions, params), block.timestamp)
);
}
function _getNormalizedBalance(address token, uint256 balance)
internal view returns (uint256 normalizedBalance)
{
return balance * 1e18 / (10 ** IERC20Like(token).decimals());
}
function _getPoolKeyAndPositionInfo(uint256 tokenId)
internal view returns (PoolKey memory poolKey, PositionInfo info)
{
return IPositionManagerLike(_POSITION_MANAGER).getPoolAndPositionInfo(tokenId);
}
function _getPoolKeyFromPoolId(bytes32 poolId) internal view returns (PoolKey memory poolKey) {
return IPositionManagerLike(_POSITION_MANAGER).poolKeys(bytes25(poolId));
}
function _getPoolKeyFromTokenId(uint256 tokenId)
internal view returns (PoolKey memory poolKey)
{
(poolKey, ) = _getPoolKeyAndPositionInfo(tokenId);
}
function _requirePoolIdMatch(bytes32 poolId, PoolKey memory poolKey) internal pure {
require(keccak256(abi.encode(poolKey)) == poolId, "MC/tokenId-poolId-mismatch");
}
}