-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathNFTXRouter.sol
912 lines (794 loc) · 29.6 KB
/
NFTXRouter.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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
// SPDX-License-Identifier: MIT
pragma solidity =0.8.15;
// inheriting
import {Pausable} from "@src/custom/Pausable.sol";
import {ERC721Holder} from "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import {ERC1155Holder} from "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
// libs
import {SafeCast} from "@uni-core/libraries/SafeCast.sol";
import {TransferLib} from "@src/lib/TransferLib.sol";
import {PoolAddress} from "@uni-periphery/libraries/PoolAddress.sol";
import {SafeERC20, IERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
// interfaces
import {IWETH9} from "@uni-periphery/interfaces/external/IWETH9.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import {IQuoterV2} from "@uni-periphery/interfaces/IQuoterV2.sol";
import {INFTXVaultV3} from "@src/interfaces/INFTXVaultV3.sol";
import {IUniswapV3Factory} from "@uni-core/interfaces/IUniswapV3Factory.sol";
import {INFTXVaultFactoryV3} from "@src/interfaces/INFTXVaultFactoryV3.sol";
import {INFTXFeeDistributorV3} from "@src/interfaces/INFTXFeeDistributorV3.sol";
import {ISwapRouter, SwapRouter} from "@uni-periphery/SwapRouter.sol";
import {INFTXInventoryStakingV3} from "@src/interfaces/INFTXInventoryStakingV3.sol";
import {IPermitAllowanceTransfer} from "@src/interfaces/external/IPermitAllowanceTransfer.sol";
import {INonfungiblePositionManager} from "@uni-periphery/interfaces/INonfungiblePositionManager.sol";
import {INFTXRouter} from "@src/interfaces/INFTXRouter.sol";
/**
* @title NFTX Router
* @author @apoorvlathey
*
* @notice Router to facilitate vault tokens minting/burning + addition/removal of concentrated liquidity
* @dev This router must be excluded from the vault fees, as vault fees handled via custom logic here. Also should be excluded from timelocks on NonfungiblePositionManager.
*/
contract NFTXRouter is INFTXRouter, Pausable, ERC721Holder, ERC1155Holder {
using SafeERC20 for IERC20;
// =============================================================
// CONSTANTS
// =============================================================
uint256 internal constant PAUSE_ADDLIQ = 0;
uint256 internal constant PAUSE_INCREASELIQ = 1;
uint256 internal constant PAUSE_REMOVELIQ = 2;
uint256 internal constant PAUSE_SELLNFTS = 3;
uint256 internal constant PAUSE_BUYNFTS = 4;
address public immutable override WETH;
IPermitAllowanceTransfer public immutable override PERMIT2;
uint256 constant BASE_VTOKEN_TIMELOCK = 1 hours;
INonfungiblePositionManager public immutable override positionManager;
SwapRouter public immutable override router;
IQuoterV2 public immutable override quoter;
INFTXVaultFactoryV3 public immutable override nftxVaultFactory;
INFTXInventoryStakingV3 public immutable override inventoryStaking;
// =============================================================
// VARIABLES
// =============================================================
uint256 public override lpTimelock;
/// @notice the max penalty applicable. The penalty goes down linearly as the `timelockedUntil` approaches
uint256 public override earlyWithdrawPenaltyInWei;
/// @notice the vToken dust amount during add/increase liquidity, above which the vTokens get staked into inventory
uint256 public override vTokenDustThreshold;
constructor(
INonfungiblePositionManager positionManager_,
SwapRouter router_,
IQuoterV2 quoter_,
INFTXVaultFactoryV3 nftxVaultFactory_,
IPermitAllowanceTransfer PERMIT2_,
uint256 lpTimelock_,
uint256 earlyWithdrawPenaltyInWei_,
uint256 vTokenDustThreshold_,
INFTXInventoryStakingV3 inventoryStaking_
) {
positionManager = positionManager_;
router = router_;
quoter = quoter_;
nftxVaultFactory = nftxVaultFactory_;
PERMIT2 = PERMIT2_;
if (lpTimelock_ == 0) revert ZeroLPTimelock();
lpTimelock = lpTimelock_;
if (earlyWithdrawPenaltyInWei_ > 1 ether)
revert InvalidEarlyWithdrawPenalty();
earlyWithdrawPenaltyInWei = earlyWithdrawPenaltyInWei_;
vTokenDustThreshold = vTokenDustThreshold_;
inventoryStaking = inventoryStaking_;
WETH = positionManager_.WETH9();
}
// =============================================================
// PUBLIC / EXTERNAL WRITE
// =============================================================
/**
* @inheritdoc INFTXRouter
*/
function addLiquidity(
AddLiquidityParams calldata params
) external payable override returns (uint256 positionId) {
INFTXVaultV3 vToken = INFTXVaultV3(
nftxVaultFactory.vault(params.vaultId)
);
if (params.vTokensAmount > 0) {
vToken.transferFrom(
msg.sender,
address(this),
params.vTokensAmount
);
}
return _addLiquidity(params, vToken);
}
/**
* @inheritdoc INFTXRouter
*/
function addLiquidityWithPermit2(
AddLiquidityParams calldata params,
bytes calldata encodedPermit2
) external payable override returns (uint256 positionId) {
INFTXVaultV3 vToken = INFTXVaultV3(
nftxVaultFactory.vault(params.vaultId)
);
if (encodedPermit2.length > 0) {
(
address owner,
IPermitAllowanceTransfer.PermitSingle memory permitSingle,
bytes memory signature
) = abi.decode(
encodedPermit2,
(address, IPermitAllowanceTransfer.PermitSingle, bytes)
);
PERMIT2.permit(owner, permitSingle, signature);
}
if (params.vTokensAmount > 0) {
PERMIT2.transferFrom(
msg.sender,
address(this),
SafeCast.toUint160(params.vTokensAmount),
address(vToken)
);
}
return _addLiquidity(params, vToken);
}
/**
* @inheritdoc INFTXRouter
*/
function increaseLiquidity(
IncreaseLiquidityParams calldata params
) external payable override {
INFTXVaultV3 vToken = INFTXVaultV3(
nftxVaultFactory.vault(params.vaultId)
);
if (params.vTokensAmount > 0) {
vToken.transferFrom(
msg.sender,
address(this),
params.vTokensAmount
);
}
return _increaseLiquidity(params, vToken);
}
/**
* @inheritdoc INFTXRouter
*/
function increaseLiquidityWithPermit2(
IncreaseLiquidityParams calldata params,
bytes calldata encodedPermit2
) external payable override {
INFTXVaultV3 vToken = INFTXVaultV3(
nftxVaultFactory.vault(params.vaultId)
);
if (encodedPermit2.length > 0) {
(
address owner,
IPermitAllowanceTransfer.PermitSingle memory permitSingle,
bytes memory signature
) = abi.decode(
encodedPermit2,
(address, IPermitAllowanceTransfer.PermitSingle, bytes)
);
PERMIT2.permit(owner, permitSingle, signature);
}
if (params.vTokensAmount > 0) {
PERMIT2.transferFrom(
msg.sender,
address(this),
SafeCast.toUint160(params.vTokensAmount),
address(vToken)
);
}
return _increaseLiquidity(params, vToken);
}
/**
* @inheritdoc INFTXRouter
*/
function removeLiquidity(
RemoveLiquidityParams calldata params
) external payable override {
onlyOwnerIfPaused(PAUSE_REMOVELIQ);
if (positionManager.ownerOf(params.positionId) != msg.sender)
revert NotPositionOwner();
// decrease liquidity of the position (this contract is excluded from the timelocks)
positionManager.decreaseLiquidity(
INonfungiblePositionManager.DecreaseLiquidityParams({
tokenId: params.positionId,
liquidity: params.liquidity,
amount0Min: params.amount0Min,
amount1Min: params.amount1Min,
deadline: params.deadline
})
);
INFTXVaultV3 vToken;
uint256 vTokenAmt;
uint256 wethAmt;
{
// collect vtokens & weth from removing liquidity + earned fees
(uint256 amount0, uint256 amount1) = positionManager.collect(
INonfungiblePositionManager.CollectParams({
tokenId: params.positionId,
recipient: address(this),
amount0Max: type(uint128).max,
amount1Max: type(uint128).max
})
);
vToken = INFTXVaultV3(nftxVaultFactory.vault(params.vaultId));
bool _isVToken0 = isVToken0(address(vToken));
(vTokenAmt, wethAmt) = _isVToken0
? (amount0, amount1)
: (amount1, amount0);
}
// checking timelock penalty
uint256 _timelockedUntil = positionManager.lockedUntil(
params.positionId
);
uint256 _timelock = positionManager.timelock(params.positionId);
if (block.timestamp <= _timelockedUntil) {
if (vTokenAmt > 0) {
// Eg: lpTimelock = 10 days, vTokenAmt = 100, penalty% = 5%
// Case 1: Instant withdraw, with 10 days left
// penaltyAmt = 100 * 5% = 5
// Case 2: With 2 days timelock left
// penaltyAmt = (100 * 5%) * 2 / 10 = 1
uint256 vTokenPenalty = ((_timelockedUntil - block.timestamp) *
vTokenAmt *
earlyWithdrawPenaltyInWei) / (_timelock * 1 ether);
// distribute this penalty
{
(, , , , uint24 fee, , , , , , , ) = positionManager
.positions(params.positionId);
address pool = IUniswapV3Factory(router.factory()).getPool(
address(vToken),
WETH,
fee
);
address feeDistributor = nftxVaultFactory.feeDistributor();
vToken.transfer(feeDistributor, vTokenPenalty);
INFTXFeeDistributorV3(feeDistributor)
.distributeVTokensToPool(
pool,
address(vToken),
vTokenPenalty
);
}
vTokenAmt -= vTokenPenalty;
}
}
// No NFTs to redeem, directly withdraw vTokens
if (params.nftIds.length == 0 && vTokenAmt > 0) {
if (msg.value > 0) revert NoETHFundsNeeded();
vToken.transfer(msg.sender, vTokenAmt);
} else {
// if withdrawn WETH is insufficient to pay for vault fees, user sends ETH (can be excess, as refunded back) along with the transaction
if (msg.value > 0) {
IWETH9(WETH).deposit{value: msg.value}();
wethAmt += msg.value;
}
// if the position has completed its timelock, then we shouldn't charge redeem fees.
bool chargeFees = positionManager.lockedUntil(params.positionId) ==
0;
// burn vTokens to provided tokenIds array. Forcing to deduct vault fees
if (chargeFees) {
TransferLib.unSafeMaxApprove(WETH, address(vToken), wethAmt);
}
uint256 vTokenBurned = params.nftIds.length * 1 ether;
if (vTokenAmt < vTokenBurned) revert InsufficientVTokens();
uint256 wethFees = vToken.redeem(
params.nftIds,
msg.sender,
wethAmt,
params.vTokenPremiumLimit,
chargeFees
);
wethAmt -= wethFees;
// if more vTokens collected than burned
uint256 vTokenResidue = vTokenAmt - vTokenBurned;
if (vTokenResidue > 0) {
vToken.transfer(msg.sender, vTokenResidue);
}
}
// convert remaining WETH to ETH & send to user
IWETH9(WETH).withdraw(wethAmt);
TransferLib.transferETH(msg.sender, wethAmt);
emit RemoveLiquidity(
params.positionId,
params.vaultId,
vTokenAmt,
wethAmt
);
}
/**
* @inheritdoc INFTXRouter
*/
function sellNFTs(
SellNFTsParams calldata params
) external payable override returns (uint256 wethReceived) {
onlyOwnerIfPaused(PAUSE_SELLNFTS);
INFTXVaultV3 vToken = INFTXVaultV3(
nftxVaultFactory.vault(params.vaultId)
);
address assetAddress = INFTXVaultV3(address(vToken)).assetAddress();
if (!vToken.is1155()) {
// tranfer NFTs from user to the vault
TransferLib.transferFromERC721(
assetAddress,
address(vToken),
params.nftIds
);
} else {
IERC1155(assetAddress).safeBatchTransferFrom(
msg.sender,
address(this),
params.nftIds,
params.nftAmounts,
""
);
IERC1155(assetAddress).setApprovalForAll(address(vToken), true);
}
// mint vToken
uint256 vTokensAmount = vToken.mint(
params.nftIds,
params.nftAmounts,
msg.sender,
address(this)
);
TransferLib.unSafeMaxApprove(
address(vToken),
address(router),
vTokensAmount
);
wethReceived = router.exactInputSingle(
ISwapRouter.ExactInputSingleParams({
tokenIn: address(vToken),
tokenOut: WETH,
fee: params.fee,
recipient: address(this),
deadline: params.deadline,
amountIn: vTokensAmount,
amountOutMinimum: params.amountOutMinimum,
sqrtPriceLimitX96: params.sqrtPriceLimitX96
})
);
// if received WETH is insufficient to pay for vault fees, user sends ETH (can be excess, as refunded back) along with the transaction
if (msg.value > 0) {
IWETH9(WETH).deposit{value: msg.value}();
wethReceived += msg.value;
}
// distributing vault fees with the wethReceived
uint256 nftCount = !vToken.is1155()
? params.nftIds.length
: _sum1155Ids(params.nftIds, params.nftAmounts);
uint256 wethFees = _ethMintFees(vToken, nftCount);
_distributeVaultFees(params.vaultId, wethFees, true);
uint256 wethRemaining = wethReceived - wethFees; // if underflow, then revert desired
// convert remaining WETH to ETH & send to user
IWETH9(WETH).withdraw(wethRemaining);
TransferLib.transferETH(msg.sender, wethRemaining);
emit SellNFTs(nftCount, wethRemaining);
}
/**
* @inheritdoc INFTXRouter
*/
function buyNFTs(BuyNFTsParams calldata params) external payable override {
onlyOwnerIfPaused(PAUSE_BUYNFTS);
INFTXVaultV3 vToken = INFTXVaultV3(
nftxVaultFactory.vault(params.vaultId)
);
uint256 vTokenAmt = params.nftIds.length * 1 ether;
IWETH9(WETH).deposit{value: msg.value}();
TransferLib.unSafeMaxApprove(WETH, address(router), msg.value);
uint256 wethSpent = router.exactOutputSingle(
ISwapRouter.ExactOutputSingleParams({
tokenIn: WETH,
tokenOut: address(vToken),
fee: params.fee,
recipient: address(this),
deadline: params.deadline,
amountOut: vTokenAmt,
amountInMaximum: msg.value,
sqrtPriceLimitX96: params.sqrtPriceLimitX96
})
);
// unwrap vTokens to tokenIds specified, and send to sender. Forcing to deduct vault fees
uint256 wethLeft = msg.value - wethSpent;
TransferLib.unSafeMaxApprove(WETH, address(vToken), wethLeft);
uint256 wethFees = vToken.redeem(
params.nftIds,
msg.sender,
wethLeft,
params.vTokenPremiumLimit,
true
);
wethLeft -= wethFees;
// refund extra ETH
if (wethLeft > 0) {
IWETH9(WETH).withdraw(wethLeft);
TransferLib.transferETH(msg.sender, wethLeft);
}
emit BuyNFTs(params.nftIds.length, wethSpent + wethFees);
}
// =============================================================
// ONLY OWNER WRITE
// =============================================================
/**
* @inheritdoc INFTXRouter
*/
function rescueTokens(IERC20 token) external override onlyOwner {
if (address(token) != address(0)) {
uint256 balance = token.balanceOf(address(this));
token.safeTransfer(msg.sender, balance);
} else {
uint256 balance = address(this).balance;
TransferLib.transferETH(msg.sender, balance);
}
}
/**
* @inheritdoc INFTXRouter
*/
function setLpTimelock(uint256 lpTimelock_) external override onlyOwner {
if (lpTimelock_ == 0) revert ZeroLPTimelock();
lpTimelock = lpTimelock_;
}
/**
* @inheritdoc INFTXRouter
*/
function setVTokenDustThreshold(
uint256 vTokenDustThreshold_
) external override onlyOwner {
vTokenDustThreshold = vTokenDustThreshold_;
}
/**
* @inheritdoc INFTXRouter
*/
function setEarlyWithdrawPenalty(
uint256 earlyWithdrawPenaltyInWei_
) external onlyOwner {
if (earlyWithdrawPenaltyInWei_ > 1 ether)
revert InvalidEarlyWithdrawPenalty();
earlyWithdrawPenaltyInWei = earlyWithdrawPenaltyInWei_;
}
// =============================================================
// PUBLIC / EXTERNAL VIEW
// =============================================================
/**
* @inheritdoc INFTXRouter
*/
function quoteBuyNFTs(
address vtoken,
uint256 nftsCount,
uint24 fee,
uint160 sqrtPriceLimitX96
) external override returns (uint256 ethRequired) {
uint256 vTokenAmt = nftsCount * 1 ether;
(ethRequired, , , ) = quoter.quoteExactOutputSingle(
IQuoterV2.QuoteExactOutputSingleParams({
tokenIn: WETH,
tokenOut: address(vtoken),
amount: vTokenAmt,
fee: fee,
sqrtPriceLimitX96: sqrtPriceLimitX96
})
);
}
/**
* @inheritdoc INFTXRouter
*/
function getPoolExists(
uint256 vaultId,
uint24 fee
) external view override returns (address pool, bool exists) {
address vToken_ = nftxVaultFactory.vault(vaultId);
pool = IUniswapV3Factory(router.factory()).getPool(vToken_, WETH, fee);
exists = pool != address(0);
}
/**
* @inheritdoc INFTXRouter
*/
function getPoolExists(
address vToken_,
uint24 fee
) external view override returns (address pool, bool exists) {
pool = IUniswapV3Factory(router.factory()).getPool(vToken_, WETH, fee);
exists = pool != address(0);
}
/**
* @inheritdoc INFTXRouter
*/
function getPool(
address vToken_,
uint24 fee
) external view override returns (address pool) {
pool = IUniswapV3Factory(router.factory()).getPool(vToken_, WETH, fee);
if (pool == address(0)) revert();
}
/**
* @inheritdoc INFTXRouter
*/
function computePool(
address vToken_,
uint24 fee
) external view override returns (address) {
return
PoolAddress.computeAddress(
router.factory(),
PoolAddress.getPoolKey(vToken_, WETH, fee)
);
}
/**
* @inheritdoc INFTXRouter
*/
function isVToken0(address vtoken) public view override returns (bool) {
return vtoken < WETH;
}
// =============================================================
// INTERNAL / PRIVATE
// =============================================================
function _addLiquidity(
AddLiquidityParams calldata params,
INFTXVaultV3 vToken
) internal returns (uint256 positionId) {
onlyOwnerIfPaused(PAUSE_ADDLIQ);
(uint256 vTokensAmount, bool _isVToken0) = _pullAndMintVTokens(
vToken,
params.nftIds,
params.nftAmounts,
!vToken.is1155(),
params.vTokensAmount
);
// creating struct first to avoid stack too deep. Variables not yet defined are set later
INonfungiblePositionManager.MintParams
memory mintParams = INonfungiblePositionManager.MintParams({
token0: address(0),
token1: address(0),
fee: params.fee,
tickLower: params.tickLower,
tickUpper: params.tickUpper,
amount0Desired: 0,
amount1Desired: 0,
amount0Min: 0,
amount1Min: 0,
recipient: params.recipient,
deadline: params.deadline
});
// mint position with vtoken and ETH
if (msg.value < params.wethMin) revert ETHValueLowerThanMin();
(
mintParams.token0,
mintParams.token1,
mintParams.amount0Desired,
mintParams.amount1Desired,
mintParams.amount0Min,
mintParams.amount1Min
) = _isVToken0
? (
address(vToken),
WETH,
vTokensAmount,
msg.value,
params.vTokenMin,
params.wethMin
)
: (
WETH,
address(vToken),
msg.value,
vTokensAmount,
params.wethMin,
params.vTokenMin
);
address pool = positionManager.createAndInitializePoolIfNecessary(
mintParams.token0,
mintParams.token1,
params.fee,
params.sqrtPriceX96
);
// mint position with vtoken and ETH
(positionId, , , ) = positionManager.mint{value: msg.value}(mintParams);
_postAddLiq(
vToken,
params.nftIds,
positionId,
params.vaultId,
params.forceTimelock,
params.recipient
);
emit AddLiquidity(
positionId,
params.vaultId,
params.vTokensAmount,
params.nftIds,
pool,
params.recipient
);
}
function _increaseLiquidity(
IncreaseLiquidityParams calldata params,
INFTXVaultV3 vToken
) internal {
onlyOwnerIfPaused(PAUSE_INCREASELIQ);
if (positionManager.ownerOf(params.positionId) != msg.sender)
revert NotPositionOwner();
(uint256 vTokensAmount, bool _isVToken0) = _pullAndMintVTokens(
vToken,
params.nftIds,
params.nftAmounts,
!vToken.is1155(),
params.vTokensAmount
);
if (msg.value < params.wethMin) revert ETHValueLowerThanMin();
(
uint256 amount0Desired,
uint256 amount1Desired,
uint256 amount0Min,
uint256 amount1Min
) = _isVToken0
? (vTokensAmount, msg.value, params.vTokenMin, params.wethMin)
: (msg.value, vTokensAmount, params.wethMin, params.vTokenMin);
positionManager.increaseLiquidity{value: msg.value}(
INonfungiblePositionManager.IncreaseLiquidityParams({
tokenId: params.positionId,
amount0Desired: amount0Desired,
amount1Desired: amount1Desired,
amount0Min: amount0Min,
amount1Min: amount1Min,
deadline: params.deadline
})
);
_postAddLiq(
vToken,
params.nftIds,
params.positionId,
params.vaultId,
params.forceTimelock,
msg.sender
);
emit IncreaseLiquidity(
params.positionId,
params.vaultId,
params.vTokensAmount,
params.nftIds
);
}
function _pullAndMintVTokens(
INFTXVaultV3 vToken,
uint256[] calldata nftIds,
uint256[] calldata nftAmounts,
bool is721,
uint256 currentVTokensAmount
) internal returns (uint256 vTokensAmount, bool _isVToken0) {
vTokensAmount = currentVTokensAmount;
if (nftIds.length > 0) {
address assetAddress = vToken.assetAddress();
if (is721) {
// tranfer NFTs from user to the vault
TransferLib.transferFromERC721(
assetAddress,
address(vToken),
nftIds
);
} else {
IERC1155(assetAddress).safeBatchTransferFrom(
msg.sender,
address(this),
nftIds,
nftAmounts,
""
);
IERC1155(assetAddress).setApprovalForAll(address(vToken), true);
}
// vault won't charge mintFees here as this contract is on exclude list
vTokensAmount += vToken.mint(
nftIds,
nftAmounts,
msg.sender,
address(this)
);
}
TransferLib.unSafeMaxApprove(
address(vToken),
address(positionManager),
vTokensAmount
);
_isVToken0 = isVToken0(address(vToken));
}
function _postAddLiq(
INFTXVaultV3 vToken,
uint256[] calldata nftIds,
uint256 positionId,
uint256 vaultId,
bool forceTimelock,
address recipient
) internal {
uint256 vTokenBalance = vToken.balanceOf(address(this));
if (nftIds.length > 0) {
// vault fees not charged, so instead update timelock of the position NFT
uint256 _lpTimelock = lpTimelock;
positionManager.setLockedUntil(
positionId,
block.timestamp + _lpTimelock,
_lpTimelock
);
if (vTokenBalance > 0) {
if (vTokenBalance > vTokenDustThreshold) {
// stake vTokens left in the inventory
TransferLib.unSafeMaxApprove(
address(vToken),
address(inventoryStaking),
vTokenBalance
);
inventoryStaking.deposit(
vaultId,
vTokenBalance,
recipient,
"",
false,
true // forceTimelock as we minted the vTokens with NFTs
);
} else {
vToken.transfer(recipient, vTokenBalance);
}
}
} else {
// if forcing timelock requested
if (forceTimelock) {
uint256 _lpTimelock = lpTimelock;
positionManager.setLockedUntil(
positionId,
block.timestamp + _lpTimelock,
_lpTimelock
);
} else {
// set timelock of the position NFT to 1 hour, to prevent instant redeem via increaseLiquidity
positionManager.setLockedUntil(
positionId,
block.timestamp + BASE_VTOKEN_TIMELOCK,
BASE_VTOKEN_TIMELOCK
);
}
// refund vTokens dust (if any left)
if (vTokenBalance > 0) {
vToken.transfer(msg.sender, vTokenBalance);
}
}
// refund extra ETH
positionManager.refundETH(msg.sender);
}
function _distributeVaultFees(
uint256 vaultId,
uint256 ethAmount,
bool isWeth
) internal {
if (ethAmount > 0) {
INFTXFeeDistributorV3 feeDistributor = INFTXFeeDistributorV3(
nftxVaultFactory.feeDistributor()
);
if (!isWeth) {
IWETH9(WETH).deposit{value: ethAmount}();
}
IWETH9(WETH).transfer(address(feeDistributor), ethAmount);
feeDistributor.distribute(vaultId);
}
}
function _sum1155Ids(
uint256[] calldata ids,
uint256[] calldata amounts
) internal pure returns (uint256 totalAmount) {
for (uint i; i < ids.length; ) {
unchecked {
// simultaneously verifies that lengths of `ids` and `amounts` match.
totalAmount += amounts[i];
++i;
}
}
}
function _ethMintFees(
INFTXVaultV3 vToken,
uint256 nftCount
) internal view returns (uint256) {
(uint256 mintFee, , ) = vToken.vaultFees();
return vToken.vTokenToETH(mintFee * nftCount);
}
receive() external payable {}
}