-
Notifications
You must be signed in to change notification settings - Fork 9
/
NFTXVaultUpgradeableV3.sol
1045 lines (895 loc) · 32.6 KB
/
NFTXVaultUpgradeableV3.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
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: MIT
pragma solidity =0.8.15;
// inheriting
import {OwnableUpgradeable} from "@src/custom/OwnableUpgradeable.sol";
import {ERC721HolderUpgradeable} from "@openzeppelin-upgradeable/contracts/token/ERC721/utils/ERC721HolderUpgradeable.sol";
import {ERC1155HolderUpgradeable} from "@openzeppelin-upgradeable/contracts/token/ERC1155/utils/ERC1155HolderUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin-upgradeable/contracts/security/ReentrancyGuardUpgradeable.sol";
import {ERC20FlashMintUpgradeable, IERC3156FlashBorrowerUpgradeable} from "@src/custom/tokens/ERC20/ERC20FlashMintUpgradeable.sol";
// libs
import {FullMath} from "@uniswap/v3-core/contracts/libraries/FullMath.sol";
import {TransferLib} from "@src/lib/TransferLib.sol";
import {FixedPoint96} from "@uniswap/v3-core/contracts/libraries/FixedPoint96.sol";
import {ExponentialPremium} from "@src/lib/ExponentialPremium.sol";
import {SafeERC20Upgradeable} from "@openzeppelin-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {EnumerableSetUpgradeable} from "@openzeppelin-upgradeable/contracts/utils/structs/EnumerableSetUpgradeable.sol";
// interfaces
import {IWETH9} from "@uni-periphery/interfaces/external/IWETH9.sol";
import {INFTXRouter} from "@src/interfaces/INFTXRouter.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {INFTXEligibility} from "@src/interfaces/INFTXEligibility.sol";
import {IDelegateRegistry} from "@src/interfaces/IDelegateRegistry.sol";
import {IERC20Upgradeable} from "@openzeppelin-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol";
import {IERC721Upgradeable} from "@openzeppelin-upgradeable/contracts/token/ERC721/IERC721Upgradeable.sol";
import {INFTXVaultFactoryV3} from "@src/interfaces/INFTXVaultFactoryV3.sol";
import {IERC1155Upgradeable} from "@openzeppelin-upgradeable/contracts/token/ERC1155/IERC1155Upgradeable.sol";
import {INFTXFeeDistributorV3} from "@src/interfaces/INFTXFeeDistributorV3.sol";
import {INFTXEligibilityManager} from "@src/interfaces/INFTXEligibilityManager.sol";
import {INFTXVaultV3} from "@src/interfaces/INFTXVaultV3.sol";
// Authors: @apoorvlathey, @0xKiwi_ and @alexgausman
contract NFTXVaultUpgradeableV3 is
INFTXVaultV3,
OwnableUpgradeable,
ERC20FlashMintUpgradeable,
ReentrancyGuardUpgradeable,
ERC721HolderUpgradeable,
ERC1155HolderUpgradeable
{
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
using SafeERC20Upgradeable for IERC20Upgradeable;
// =============================================================
// CONSTANTS
// =============================================================
uint256 constant BASE = 10 ** 18;
IWETH9 public immutable override WETH;
address constant CRYPTO_PUNKS = 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB;
address constant CRYPTO_KITTIES =
0x06012c8cf97BEaD5deAe237070F9587f8E7A266d;
IDelegateRegistry constant DELEGATE_REGISTRY =
IDelegateRegistry(0x00000000000000447e69651d841bD8D104Bed493);
// "constants": only set during initialization
address public override assetAddress;
INFTXVaultFactoryV3 public override vaultFactory;
uint256 public override vaultId;
bool public override is1155;
// =============================================================
// VARIABLES
// =============================================================
address public override manager;
INFTXEligibility public override eligibilityStorage;
bool public override allowAllItems;
bool public override enableMint;
bool public override enableRedeem;
bool public override enableSwap;
EnumerableSetUpgradeable.UintSet internal _holdings;
// tokenId => qty
mapping(uint256 => uint256) internal _quantity1155;
// tokenId => info
mapping(uint256 => TokenDepositInfo) public override tokenDepositInfo;
/**
* For ERC1155 deposits, per TokenId:
*
* pointerIndex1155
* |
* V
* [{qty: 0, depositor: A}, {qty: 5, depositor: B}, {qty: 10, depositor: C}, ...]
*
* New deposits are pushed to the end of array, and the oldest remaining deposit is used while withdrawing, hence following FIFO.
*/
// tokenId => info[]
mapping(uint256 => DepositInfo1155[]) public override depositInfo1155;
// tokenId => pointerIndex
mapping(uint256 => uint256) public override pointerIndex1155;
// =============================================================
// INIT
// =============================================================
constructor(IWETH9 WETH_) {
WETH = WETH_;
}
function __NFTXVault_init(
string calldata name_,
string calldata symbol_,
address assetAddress_,
bool is1155_,
bool allowAllItems_
) public override initializer {
__Ownable_init();
__ERC20_init(name_, symbol_);
if (assetAddress_ == address(0)) revert ZeroAddress();
assetAddress = assetAddress_;
vaultFactory = INFTXVaultFactoryV3(msg.sender);
vaultId = INFTXVaultFactoryV3(msg.sender).numVaults();
is1155 = is1155_;
allowAllItems = allowAllItems_;
emit VaultInit(vaultId, assetAddress_, is1155_, allowAllItems_);
setVaultFeatures(
true /*enableMint*/,
true /*enableRedeem*/,
true /*enableSwap*/
);
DELEGATE_REGISTRY.delegateAll(
// Set NFTXVaultFactory's owner (DAO) as the delegate.
OwnableUpgradeable(msg.sender).owner(),
bytes32(""),
true
);
}
// =============================================================
// PUBLIC / EXTERNAL WRITE
// =============================================================
/**
* @inheritdoc INFTXVaultV3
*/
function mint(
uint256[] calldata tokenIds,
uint256[] calldata amounts,
address depositor,
address to
) external payable override nonReentrant returns (uint256 vTokensMinted) {
_onlyOwnerIfPaused(1);
if (!enableMint) revert MintingDisabled();
// Take the NFTs.
uint256 nftCount = _receiveNFTs(depositor, tokenIds, amounts);
vTokensMinted = BASE * nftCount;
// Mint to the user.
_mint(to, vTokensMinted);
(uint256 mintFee, , ) = vaultFees();
uint256 totalVTokenFee = mintFee * nftCount;
uint256 ethFees = _chargeAndDistributeFees(totalVTokenFee, msg.value);
_refundETH(msg.value, ethFees);
emit Minted(tokenIds, amounts, to, depositor);
}
/**
* @inheritdoc INFTXVaultV3
*/
function redeem(
uint256[] calldata idsOut,
address to,
uint256 wethAmount,
uint256 vTokenPremiumLimit,
bool forceFees
) external payable override nonReentrant returns (uint256 ethFees) {
_onlyOwnerIfPaused(2);
if (!enableRedeem) revert RedeemDisabled();
uint256 ethOrWethAmt;
if (wethAmount > 0) {
if (msg.value > 0) revert ETHSent();
ethOrWethAmt = wethAmount;
} else {
ethOrWethAmt = msg.value;
}
uint256 totalVaultFee;
{
uint256 count = idsOut.length;
// burn from the sender.
_burn(msg.sender, BASE * count);
{
(, uint256 redeemFee, ) = vaultFees();
totalVaultFee = (redeemFee * count);
}
}
// Withdraw from vault.
INFTXVaultFactoryV3 _vaultFactory = vaultFactory;
bool deductFees = forceFees ||
!_vaultFactory.excludedFromFees(msg.sender);
(
uint256 netVTokenPremium,
uint256[] memory vTokenPremiums,
address[] memory depositors
) = _withdrawNFTsTo(idsOut, to, deductFees, _vaultFactory);
if (deductFees) {
if (netVTokenPremium > vTokenPremiumLimit)
revert PremiumLimitExceeded();
ethFees = _chargeAndDistributeFeesForRedeem(
ethOrWethAmt,
msg.value > 0,
totalVaultFee,
netVTokenPremium,
vTokenPremiums,
depositors
);
}
if (msg.value > 0) {
_refundETH(msg.value, ethFees);
}
emit Redeemed(idsOut, to);
}
/**
* @inheritdoc INFTXVaultV3
*/
function swap(
uint256[] calldata idsIn,
uint256[] calldata amounts,
uint256[] calldata idsOut,
address depositor,
address to,
uint256 vTokenPremiumLimit,
bool forceFees
) external payable override nonReentrant returns (uint256 ethFees) {
_onlyOwnerIfPaused(3);
if (!enableSwap) revert SwapDisabled();
{
uint256 count;
if (is1155) {
uint256 len = idsIn.length;
for (uint256 i; i < len; ) {
if (amounts[i] == 0) revert TransferAmountIsZero();
count += amounts[i];
unchecked {
++i;
}
}
} else {
count = idsIn.length;
}
if (count != idsOut.length) revert TokenLengthMismatch();
}
{
(, , uint256 swapFee) = vaultFees();
uint256 totalVaultFee = (swapFee * idsOut.length);
// Give the NFTs first, so the user wont get the same thing back.
INFTXVaultFactoryV3 _vaultFactory = vaultFactory;
bool deductFees = forceFees ||
!_vaultFactory.excludedFromFees(msg.sender);
(
uint256 netVTokenPremium,
uint256[] memory vTokenPremiums,
address[] memory depositors
) = _withdrawNFTsTo(idsOut, to, deductFees, _vaultFactory);
if (deductFees) {
if (netVTokenPremium > vTokenPremiumLimit)
revert PremiumLimitExceeded();
ethFees = _chargeAndDistributeFeesForRedeem(
msg.value,
true,
totalVaultFee,
netVTokenPremium,
vTokenPremiums,
depositors
);
}
}
_receiveNFTs(depositor, idsIn, amounts);
_refundETH(msg.value, ethFees);
emit Swapped(idsIn, amounts, idsOut, to, depositor);
}
/**
* @inheritdoc INFTXVaultV3
*/
function flashLoan(
IERC3156FlashBorrowerUpgradeable receiver,
address token,
uint256 amount,
bytes calldata data
) public override(ERC20FlashMintUpgradeable, INFTXVaultV3) returns (bool) {
_onlyOwnerIfPaused(4);
return super.flashLoan(receiver, token, amount, data);
}
// =============================================================
// ONLY PRIVILEGED WRITE
// =============================================================
/**
* @inheritdoc INFTXVaultV3
*/
function finalizeVault() external override {
_onlyPrivileged();
setManager(address(0));
}
/**
* @inheritdoc INFTXVaultV3
*/
function setVaultMetadata(
string calldata name_,
string calldata symbol_
) external override {
_onlyPrivileged();
_setMetadata(name_, symbol_);
}
/**
* @inheritdoc INFTXVaultV3
*/
function setVaultFeatures(
bool enableMint_,
bool enableRedeem_,
bool enableSwap_
) public override {
_onlyPrivileged();
enableMint = enableMint_;
enableRedeem = enableRedeem_;
enableSwap = enableSwap_;
emit EnableMintUpdated(enableMint_);
emit EnableRedeemUpdated(enableRedeem_);
emit EnableSwapUpdated(enableSwap_);
}
/**
* @inheritdoc INFTXVaultV3
*/
function setFees(
uint256 mintFee_,
uint256 redeemFee_,
uint256 swapFee_
) external override {
_onlyPrivileged();
vaultFactory.setVaultFees(vaultId, mintFee_, redeemFee_, swapFee_);
}
/**
* @inheritdoc INFTXVaultV3
*/
function disableVaultFees() external override {
_onlyPrivileged();
vaultFactory.disableVaultFees(vaultId);
}
/**
* @inheritdoc INFTXVaultV3
*/
function deployEligibilityStorage(
uint256 moduleIndex,
bytes calldata initData
) external override returns (address) {
_onlyPrivileged();
if (address(eligibilityStorage) != address(0))
revert EligibilityAlreadySet();
INFTXEligibilityManager eligManager = INFTXEligibilityManager(
vaultFactory.eligibilityManager()
);
address _eligibility = eligManager.deployEligibility(
moduleIndex,
initData
);
eligibilityStorage = INFTXEligibility(_eligibility);
// Toggle this to let the contract know to check eligibility now.
allowAllItems = false;
emit EligibilityDeployed(moduleIndex, _eligibility);
return _eligibility;
}
/**
* @inheritdoc INFTXVaultV3
*/
function setManager(address manager_) public override {
_onlyPrivileged();
manager = manager_;
emit ManagerSet(manager_);
}
/**
* @inheritdoc INFTXVaultV3
*/
function updateDelegate() external {
_onlyPrivileged();
DELEGATE_REGISTRY.delegateAll(
OwnableUpgradeable(address(vaultFactory)).owner(),
bytes32(""),
true
);
}
// =============================================================
// ONLY OWNER WRITE
// =============================================================
/**
* @inheritdoc INFTXVaultV3
*/
function rescueTokens(
TokenType tt,
address token,
uint256[] calldata ids,
uint256[] calldata amounts
) external onlyOwner {
if (address(token) == assetAddress) revert CantRescueAssetToken();
if (tt == TokenType.ERC20) {
uint256 balance = IERC20Upgradeable(token).balanceOf(address(this));
IERC20Upgradeable(token).safeTransfer(msg.sender, balance);
} else if (tt == TokenType.ERC721) {
uint256 len = ids.length;
for (uint256 i; i < len; ) {
_transferERC721(token, msg.sender, ids[i]);
unchecked {
++i;
}
}
} else {
IERC1155Upgradeable(token).safeBatchTransferFrom(
address(this),
msg.sender,
ids,
amounts,
""
);
}
}
function shutdown(
address recipient,
uint256[] calldata tokenIds
) external override onlyOwner {
uint256 numItems = totalSupply() / BASE;
if (numItems > 4) revert TooManyItems();
_withdrawNFTsTo(tokenIds, recipient, false, vaultFactory);
emit VaultShutdown(assetAddress, numItems, recipient);
assetAddress = address(0);
}
// =============================================================
// PUBLIC / EXTERNAL VIEW
// =============================================================
/**
* @inheritdoc INFTXVaultV3
*/
function vaultFees()
public
view
override
returns (uint256 mintFee, uint256 redeemFee, uint256 swapFee)
{
return vaultFactory.vaultFees(vaultId);
}
/**
* @inheritdoc INFTXVaultV3
*/
function allValidNFTs(
uint256[] memory tokenIds
) public view override returns (bool) {
if (allowAllItems) {
return true;
}
INFTXEligibility _eligibilityStorage = eligibilityStorage;
if (address(_eligibilityStorage) == address(0)) {
return false;
}
return _eligibilityStorage.checkAllEligible(tokenIds);
}
/**
* @inheritdoc INFTXVaultV3
*/
function nftIdAt(
uint256 holdingsIndex
) external view override returns (uint256) {
return _holdings.at(holdingsIndex);
}
/**
* @inheritdoc INFTXVaultV3
*/
function allHoldings() external view override returns (uint256[] memory) {
uint256 len = _holdings.length();
uint256[] memory idArray = new uint256[](len);
for (uint256 i; i < len; ) {
idArray[i] = _holdings.at(i);
unchecked {
++i;
}
}
return idArray;
}
/**
* @inheritdoc INFTXVaultV3
*/
function totalHoldings() external view override returns (uint256) {
return _holdings.length();
}
/**
* @inheritdoc INFTXVaultV3
*/
function holdingsContains(
uint256 tokenId
) external view override returns (bool) {
return _holdings.contains(tokenId);
}
/**
* @inheritdoc INFTXVaultV3
*/
function version() external pure override returns (string memory) {
return "v3.0.0";
}
/**
* @inheritdoc INFTXVaultV3
*/
function vTokenToETH(
uint256 vTokenAmount
) external view override returns (uint256 ethAmount) {
(ethAmount, ) = _vTokenToETH(vaultFactory, vTokenAmount);
}
/**
* @inheritdoc INFTXVaultV3
*/
function depositInfo1155Length(
uint256 tokenId
) external view override returns (uint256) {
return depositInfo1155[tokenId].length;
}
// =============================================================
// INTERNAL HELPERS
// =============================================================
function _flashFee(
address /** token */,
uint256 amount
) internal view override returns (uint256) {
(uint256 mintFee, uint256 redeemFee, uint256 swapFee) = vaultFees();
uint256 maxFee = mintFee;
if (redeemFee > maxFee) {
maxFee = redeemFee;
}
if (swapFee > maxFee) {
maxFee = swapFee;
}
return (amount * maxFee) / BASE;
}
function _flashFeeReceiver() internal view override returns (address) {
return
address(
INFTXFeeDistributorV3(vaultFactory.feeDistributor())
.inventoryStaking()
);
}
// We set a hook to the eligibility module (if it exists) after redeems in case anything needs to be modified.
function _afterRedeemHook(uint256[] memory tokenIds) internal {
INFTXEligibility _eligibilityStorage = eligibilityStorage;
if (address(_eligibilityStorage) == address(0)) {
return;
}
_eligibilityStorage.afterRedeemHook(tokenIds);
}
function _receiveNFTs(
address depositor,
uint256[] calldata tokenIds,
uint256[] calldata amounts
) internal returns (uint256) {
if (!allValidNFTs(tokenIds)) revert NotEligible();
if (!is1155) {
address _assetAddress = assetAddress;
uint256 len = tokenIds.length;
for (uint256 i; i < len; ) {
uint256 tokenId = tokenIds[i];
// We may already own the NFT here so we check in order:
// Does the vault own it?
// - If so, check if its in holdings list
// - If so, we reject. This means the NFT has already been claimed for.
// - If not, it means we have not yet accounted for this NFT, so we continue.
// -If not, we "pull" it from the msg.sender and add to holdings.
_transferFromERC721(_assetAddress, tokenId);
if (!_holdings.add(tokenId)) revert HoldingsUpdationFailed();
tokenDepositInfo[tokenId] = TokenDepositInfo({
timestamp: uint48(block.timestamp),
depositor: depositor
});
unchecked {
++i;
}
}
return len;
} else {
// This is technically a check, so placing it before the effect.
IERC1155Upgradeable(assetAddress).safeBatchTransferFrom(
msg.sender,
address(this),
tokenIds,
amounts,
""
);
uint256 count;
uint256 len = tokenIds.length;
for (uint256 i; i < len; ) {
uint256 tokenId = tokenIds[i];
uint256 amount = amounts[i];
if (amount == 0) revert TransferAmountIsZero();
if (_quantity1155[tokenId] == 0) {
if (!_holdings.add(tokenId))
revert HoldingsUpdationFailed();
}
_quantity1155[tokenId] += amount;
count += amount;
depositInfo1155[tokenId].push(
DepositInfo1155({
qty: amount,
depositor: depositor,
timestamp: uint48(block.timestamp)
})
);
unchecked {
++i;
}
}
return count;
}
}
function _withdrawNFTsTo(
uint256[] memory specificIds,
address to,
bool deductFees,
INFTXVaultFactoryV3 _vaultFactory
)
internal
returns (
uint256 netVTokenPremium,
uint256[] memory vTokenPremiums,
address[] memory depositors
)
{
// cache
bool _is1155 = is1155;
address _assetAddress = assetAddress;
uint256 premiumMax;
uint256 premiumDuration;
if (deductFees) {
premiumMax = _vaultFactory.premiumMax();
premiumDuration = _vaultFactory.premiumDuration();
vTokenPremiums = new uint256[](specificIds.length);
depositors = new address[](specificIds.length);
}
uint256 len = specificIds.length;
for (uint256 i; i < len; ) {
uint256 tokenId = specificIds[i];
if (_is1155) {
{
uint256 _qty1155 = _quantity1155[tokenId];
if (_qty1155 == 0) revert IdNotFound();
_quantity1155[tokenId] = _qty1155 - 1;
// updated _quantity1155 is 0 now, so remove from holdings
if (_qty1155 == 1) {
if (!_holdings.remove(tokenId))
revert HoldingsUpdationFailed();
}
}
IERC1155Upgradeable(_assetAddress).safeTransferFrom(
address(this),
to,
tokenId,
1,
""
);
uint256 _pointerIndex1155 = pointerIndex1155[tokenId];
DepositInfo1155 storage depositInfo = depositInfo1155[tokenId][
_pointerIndex1155
];
uint256 _qty = depositInfo.qty;
depositInfo.qty = _qty - 1;
// if it was the last nft from this deposit
if (_qty == 1) {
pointerIndex1155[tokenId] = _pointerIndex1155 + 1;
}
if (deductFees) {
uint256 vTokenPremium = _getVTokenPremium(
depositInfo.timestamp,
premiumMax,
premiumDuration
);
netVTokenPremium += vTokenPremium;
vTokenPremiums[i] = vTokenPremium;
depositors[i] = depositInfo.depositor;
}
} else {
if (deductFees) {
TokenDepositInfo memory depositInfo = tokenDepositInfo[
tokenId
];
uint256 vTokenPremium = _getVTokenPremium(
depositInfo.timestamp,
premiumMax,
premiumDuration
);
netVTokenPremium += vTokenPremium;
vTokenPremiums[i] = vTokenPremium;
depositors[i] = depositInfo.depositor;
}
if (!_holdings.remove(tokenId)) revert HoldingsUpdationFailed();
_transferERC721(_assetAddress, to, tokenId);
}
unchecked {
++i;
}
}
_afterRedeemHook(specificIds);
}
/// @dev Uses TWAP to calculate fees `ethAmount` corresponding to the given `vTokenAmount`
/// Returns 0 if pool doesn't exist or sender is excluded from fees.
function _chargeAndDistributeFees(
uint256 vTokenFeeAmount,
uint256 ethReceived
) internal returns (uint256 ethAmount) {
// cache
INFTXVaultFactoryV3 _vaultFactory = vaultFactory;
if (_vaultFactory.excludedFromFees(msg.sender)) {
return 0;
}
INFTXFeeDistributorV3 feeDistributor;
(ethAmount, feeDistributor) = _vTokenToETH(
_vaultFactory,
vTokenFeeAmount
);
if (ethAmount > 0) {
if (ethReceived < ethAmount) revert InsufficientETHSent();
WETH.deposit{value: ethAmount}();
WETH.transfer(address(feeDistributor), ethAmount);
emit FeesDistributed(ethAmount);
feeDistributor.distribute(vaultId);
}
}
function _chargeAndDistributeFeesForRedeem(
uint256 ethOrWethReceived,
bool isETH,
uint256 totalVaultFees,
uint256 netVTokenPremium,
uint256[] memory vTokenPremiums,
address[] memory depositors
) internal returns (uint256 ethAmount) {
uint256 vaultETHFees;
INFTXFeeDistributorV3 feeDistributor;
(vaultETHFees, feeDistributor) = _vTokenToETH(
vaultFactory,
totalVaultFees
);
if (vaultETHFees > 0) {
uint256 netETHPremium;
uint256 netETHPremiumForDepositors;
if (netVTokenPremium > 0) {
netETHPremium =
(vaultETHFees * netVTokenPremium) /
totalVaultFees;
netETHPremiumForDepositors =
(netETHPremium * vaultFactory.depositorPremiumShare()) /
1 ether;
}
ethAmount = vaultETHFees + netETHPremium;
if (ethOrWethReceived < ethAmount) revert InsufficientETHSent();
if (isETH) {
WETH.deposit{value: ethAmount}();
} else {
// pull only required weth from sender
WETH.transferFrom(msg.sender, address(this), ethAmount);
}
uint256 sumWethPremium;
uint256 len = vTokenPremiums.length;
for (uint256 i; i < len; ) {
if (vTokenPremiums[i] > 0) {
uint256 wethPremium = (netETHPremiumForDepositors *
vTokenPremiums[i]) / netVTokenPremium;
WETH.transfer(depositors[i], wethPremium);
sumWethPremium += wethPremium;
emit PremiumShared(depositors[i], wethPremium);
}
unchecked {
++i;
}
}
uint256 feeToDistribute = ethAmount - sumWethPremium;
WETH.transfer(address(feeDistributor), feeToDistribute);
emit FeesDistributed(feeToDistribute);
feeDistributor.distribute(vaultId);
}
}
function _vTokenToETH(
INFTXVaultFactoryV3 _vaultFactory,
uint256 vTokenAmount
)
internal
view
returns (uint256 ethAmount, INFTXFeeDistributorV3 feeDistributor)
{
feeDistributor = INFTXFeeDistributorV3(_vaultFactory.feeDistributor());
INFTXRouter nftxRouter = INFTXRouter(feeDistributor.nftxRouter());
(address pool, bool exists) = nftxRouter.getPoolExists(
address(this),
feeDistributor.rewardFeeTier()
);
if (!exists) {
return (0, feeDistributor);
}
// price = amount1 / amount0
// priceX96 = price * 2^96
uint256 priceX96 = vaultFactory.getTwapX96(pool);
if (priceX96 == 0) return (0, feeDistributor);
if (
address(this) < address(WETH) // checking if isVToken0
) {
ethAmount = FullMath.mulDiv(
vTokenAmount,
priceX96,
FixedPoint96.Q96
);
} else {
ethAmount = FullMath.mulDiv(
vTokenAmount,
FixedPoint96.Q96,
priceX96
);
}
}
function _getVTokenPremium(
uint48 timestamp,
uint256 premiumMax,
uint256 premiumDuration
) internal view returns (uint256) {
return
ExponentialPremium.getPremium(
timestamp,
premiumMax,
premiumDuration
);
}
/// @dev Must satisfy ethReceived >= ethFees
function _refundETH(uint256 ethReceived, uint256 ethFees) internal {
uint256 ethRefund = ethReceived - ethFees;
if (ethRefund > 0) {
TransferLib.transferETH(msg.sender, ethRefund);
}
}
function _transferERC721(
address assetAddr,
address to,
uint256 tokenId
) internal {
bytes memory data;
if (assetAddr != CRYPTO_PUNKS && assetAddr != CRYPTO_KITTIES) {
// Default
data = abi.encodeWithSignature(
"safeTransferFrom(address,address,uint256)",
address(this),
to,
tokenId
);
} else if (assetAddr == CRYPTO_PUNKS) {
data = abi.encodeWithSignature(
"transferPunk(address,uint256)",
to,
tokenId
);
} else {
data = abi.encodeWithSignature(
"transfer(address,uint256)",
to,
tokenId
);
}
(bool success, bytes memory returnData) = address(assetAddr).call(data);
require(success, string(returnData));
}
function _transferFromERC721(address assetAddr, uint256 tokenId) internal {
bytes memory data;
if (assetAddr != CRYPTO_PUNKS && assetAddr != CRYPTO_KITTIES) {
// Default
// Allow other contracts to "push" into the vault, safely.
// If we already have the token requested, make sure we don't have it in the list to prevent duplicate minting.
if (
IERC721Upgradeable(assetAddress).ownerOf(tokenId) ==
address(this)
) {
if (_holdings.contains(tokenId)) revert NFTAlreadyOwned();
return;
} else {
data = abi.encodeWithSignature(
"safeTransferFrom(address,address,uint256)",