-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathVault.sol
1251 lines (1032 loc) · 37.9 KB
/
Vault.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: UNLICENSED
pragma solidity =0.8.10;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Context} from "@openzeppelin/contracts/utils/Context.sol";
import {ERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {Pausable} from "@openzeppelin/contracts/security/Pausable.sol";
import {Counters} from "@openzeppelin/contracts/utils/Counters.sol";
import {IVault} from "./vault/IVault.sol";
import {IVaultSponsoring} from "./vault/IVaultSponsoring.sol";
import {IVaultSettings} from "./vault/IVaultSettings.sol";
import {CurveSwapper} from "./vault/CurveSwapper.sol";
import {PercentMath} from "./lib/PercentMath.sol";
import {ExitPausable} from "./lib/ExitPausable.sol";
import {IStrategy} from "./strategy/IStrategy.sol";
import {CustomErrors} from "./interfaces/CustomErrors.sol";
/**
* A vault where other accounts can deposit an underlying token
* currency and set distribution params for their principal and yield
*
* @notice The underlying token can be automatically swapped from any configured ERC20 token via {CurveSwapper}
*/
contract Vault is
IVault,
IVaultSponsoring,
IVaultSettings,
CurveSwapper,
Context,
ERC165,
AccessControl,
ReentrancyGuard,
Pausable,
ExitPausable,
CustomErrors
{
using SafeERC20 for IERC20;
using SafeERC20 for IERC20Metadata;
using PercentMath for uint256;
using PercentMath for uint16;
using Counters for Counters.Counter;
//
// Constants
//
/// Role allowed to invest/desinvest from strategy
bytes32 public constant KEEPER_ROLE = keccak256("KEEPER_ROLE");
/// Role allowed to change settings such as performance fee and investment fee
bytes32 public constant SETTINGS_ROLE = keccak256("SETTINGS_ROLE");
/// Role for sponsors allowed to call sponsor/unsponsor
bytes32 public constant SPONSOR_ROLE = keccak256("SPONSOR_ROLE");
/// Minimum lock for each sponsor
uint64 public constant MIN_SPONSOR_LOCK_DURATION = 2 weeks;
/// Maximum lock for each sponsor
uint64 public constant MAX_SPONSOR_LOCK_DURATION = 24 weeks;
/// Maximum lock for each deposit
uint64 public constant MAX_DEPOSIT_LOCK_DURATION = 24 weeks;
/// Helper constant for computing shares without losing precision
uint256 public constant SHARES_MULTIPLIER = 1e18;
//
// State
//
/// @inheritdoc IVault
IERC20Metadata public immutable override(IVault) underlying;
/// @inheritdoc IVault
uint16 public override(IVault) investPct;
/// @inheritdoc IVault
uint64 public immutable override(IVault) minLockPeriod;
/// @inheritdoc IVaultSponsoring
uint256 public override(IVaultSponsoring) totalSponsored;
/// @inheritdoc IVault
uint256 public override(IVault) totalShares;
/// @inheritdoc IVault
uint16 public override(IVault) immediateInvestLimitPct;
/// The investment strategy
IStrategy public strategy;
/// Unique IDs to correlate donations that belong to the same foundation
uint256 private _depositGroupIds;
mapping(uint256 => address) public depositGroupIdOwner;
/// deposit ID => deposit data
mapping(uint256 => Deposit) public deposits;
/// Counter for deposit ids
Counters.Counter private _depositTokenIds;
/// claimer address => claimer data
mapping(address => Claimer) public claimers;
/// The total of principal deposited
uint256 public override(IVault) totalPrincipal;
/// Treasury address to collect performance fee
address public treasury;
/// Performance fee percentage
uint16 public perfFeePct;
/// Current accumulated performance fee;
uint256 public accumulatedPerfFee;
/// Loss tolerance pct
uint16 public lossTolerancePct;
/// Rebalance minimum
uint256 private immutable rebalanceMinimum;
/**
* @param _underlying Underlying ERC20 token to use.
* @param _minLockPeriod Minimum lock period to deposit
* @param _investPct Percentage of the total underlying to invest in the strategy
* @param _treasury Treasury address to collect performance fee
* @param _admin Vault admin address
* @param _perfFeePct Performance fee percentage
* @param _lossTolerancePct Loss tolerance when investing through the strategy
* @param _swapPools Swap pools used to automatically convert tokens to underlying
*/
constructor(
IERC20Metadata _underlying,
uint64 _minLockPeriod,
uint16 _investPct,
address _treasury,
address _admin,
uint16 _perfFeePct,
uint16 _lossTolerancePct,
SwapPoolParam[] memory _swapPools,
uint16 _immediateInvestLimitPct
) {
if (!_immediateInvestLimitPct.validPct())
revert VaultInvalidImmediateInvestLimitPct();
if (!_investPct.validPct()) revert VaultInvalidInvestPct();
if (!_perfFeePct.validPct()) revert VaultInvalidPerformanceFee();
if (!_lossTolerancePct.validPct()) revert VaultInvalidLossTolerance();
if (address(_underlying) == address(0x0))
revert VaultUnderlyingCannotBe0Address();
if (_treasury == address(0x0)) revert VaultTreasuryCannotBe0Address();
if (_admin == address(0x0)) revert VaultAdminCannotBe0Address();
if (_minLockPeriod == 0 || _minLockPeriod > MAX_DEPOSIT_LOCK_DURATION)
revert VaultInvalidMinLockPeriod();
_grantRole(DEFAULT_ADMIN_ROLE, _admin);
_grantRole(KEEPER_ROLE, _admin);
_grantRole(SETTINGS_ROLE, _admin);
_grantRole(SPONSOR_ROLE, _admin);
investPct = _investPct;
underlying = _underlying;
treasury = _treasury;
minLockPeriod = _minLockPeriod;
perfFeePct = _perfFeePct;
lossTolerancePct = _lossTolerancePct;
immediateInvestLimitPct = _immediateInvestLimitPct;
rebalanceMinimum = 10 * 10**underlying.decimals();
_addPools(_swapPools);
emit TreasuryUpdated(_treasury);
}
//
// Modifiers
//
modifier onlyAdmin() {
if (!hasRole(DEFAULT_ADMIN_ROLE, msg.sender))
revert VaultCallerNotAdmin();
_;
}
modifier onlySettings() {
if (!hasRole(SETTINGS_ROLE, msg.sender))
revert VaultCallerNotSettings();
_;
}
modifier onlyKeeper() {
if (!hasRole(KEEPER_ROLE, msg.sender)) revert VaultCallerNotKeeper();
_;
}
modifier onlySponsor() {
if (!hasRole(SPONSOR_ROLE, msg.sender)) revert VaultCallerNotSponsor();
_;
}
/**
* Transfers administrator rights for the Vault to another account,
* revoking all current admin's roles and setting up the roles for the new admin.
*
* @notice Can only be called by the admin.
*
* @param _newAdmin The new admin account.
*/
function transferAdminRights(address _newAdmin) external onlyAdmin {
if (_newAdmin == address(0x0)) revert VaultAdminCannotBe0Address();
if (_newAdmin == msg.sender)
revert VaultCannotTransferAdminRightsToSelf();
_grantRole(DEFAULT_ADMIN_ROLE, _newAdmin);
_grantRole(KEEPER_ROLE, _newAdmin);
_grantRole(SETTINGS_ROLE, _newAdmin);
_grantRole(SPONSOR_ROLE, _newAdmin);
_revokeRole(DEFAULT_ADMIN_ROLE, msg.sender);
_revokeRole(KEEPER_ROLE, msg.sender);
_revokeRole(SETTINGS_ROLE, msg.sender);
_revokeRole(SPONSOR_ROLE, msg.sender);
}
//
// IVault
//
/// @inheritdoc IVault
function totalUnderlying() public view override(IVault) returns (uint256) {
if (address(strategy) != address(0)) {
return
underlying.balanceOf(address(this)) + strategy.investedAssets();
}
return underlying.balanceOf(address(this));
}
/// @inheritdoc IVault
function yieldFor(address _to)
public
view
override(IVault)
returns (
uint256 claimableYield,
uint256 shares,
uint256 perfFee
)
{
uint256 claimerPrincipal = claimers[_to].totalPrincipal;
uint256 claimerShares = claimers[_to].totalShares;
uint256 _totalUnderlyingMinusSponsored = totalUnderlyingMinusSponsored();
uint256 currentClaimerPrincipal = _computeAmount(
claimerShares,
totalShares,
_totalUnderlyingMinusSponsored
);
if (currentClaimerPrincipal <= claimerPrincipal) {
return (0, 0, 0);
}
uint256 yieldWithPerfFee = currentClaimerPrincipal - claimerPrincipal;
shares = _computeShares(
yieldWithPerfFee,
totalShares,
_totalUnderlyingMinusSponsored
);
uint256 sharesAmount = _computeAmount(
shares,
totalShares,
_totalUnderlyingMinusSponsored
);
perfFee = sharesAmount.pctOf(perfFeePct);
claimableYield = sharesAmount - perfFee;
}
/// @inheritdoc IVault
function depositForGroupId(uint256 _groupId, DepositParams calldata _params)
external
nonReentrant
whenNotPaused
returns (uint256[] memory depositIds)
{
if (depositGroupIdOwner[_groupId] != msg.sender)
revert VaultSenderNotOwnerOfGroupId();
depositIds = _doDeposit(_groupId, _params);
}
/// @inheritdoc IVault
function deposit(DepositParams calldata _params)
external
nonReentrant
whenNotPaused
returns (uint256[] memory depositIds)
{
uint256 depositGroupId = _depositGroupIds;
_depositGroupIds = depositGroupId + 1;
depositGroupIdOwner[depositGroupId] = msg.sender;
depositIds = _doDeposit(depositGroupId, _params);
}
function _doDeposit(uint256 _groupId, DepositParams calldata _params)
internal
returns (uint256[] memory depositIds)
{
if (_params.amount == 0) revert VaultCannotDeposit0();
if (
_params.lockDuration < minLockPeriod ||
_params.lockDuration > MAX_DEPOSIT_LOCK_DURATION
) revert VaultInvalidLockPeriod();
if (bytes(_params.name).length < 3) revert VaultDepositNameTooShort();
uint256 principalMinusStrategyFee = _applyLossTolerance(totalPrincipal);
uint256 previousTotalUnderlying = totalUnderlyingMinusSponsored();
if (principalMinusStrategyFee > previousTotalUnderlying)
revert VaultCannotDepositWhenYieldNegative();
_transferAndCheckInputToken(
msg.sender,
_params.inputToken,
_params.amount
);
uint256 newUnderlyingAmount = _swapIntoUnderlying(
_params.inputToken,
_params.amount,
_params.slippage
);
uint64 lockedUntil = _params.lockDuration + _blockTimestamp();
depositIds = _createDeposit(
previousTotalUnderlying,
newUnderlyingAmount,
lockedUntil,
_params.claims,
_params.name,
_groupId
);
if (immediateInvestLimitPct != 0) _immediateInvestment();
}
/// @inheritdoc IVault
function claimYield(address _to)
external
override(IVault)
nonReentrant
whenNotExitPaused
{
if (_to == address(0)) revert VaultDestinationCannotBe0Address();
(uint256 yield, uint256 shares, uint256 fee) = yieldFor(msg.sender);
if (yield == 0) revert VaultNoYieldToClaim();
uint256 _totalUnderlyingMinusSponsored = totalUnderlyingMinusSponsored();
uint256 _totalShares = totalShares;
accumulatedPerfFee += fee;
claimers[msg.sender].totalShares -= shares;
totalShares -= shares;
emit YieldClaimed(
msg.sender,
_to,
yield,
shares,
fee,
_totalUnderlyingMinusSponsored,
_totalShares
);
if (address(strategy) != address(0)) {
uint256 yieldTransferred = strategy.transferYield(_to, yield);
if (yieldTransferred >= yield) {
return;
}
yield -= yieldTransferred;
}
_rebalanceBeforeWithdrawing(yield);
underlying.safeTransfer(_to, yield);
}
/// @inheritdoc IVault
function withdraw(address _to, uint256[] calldata _ids)
external
override(IVault)
nonReentrant
whenNotExitPaused
{
if (_to == address(0)) revert VaultDestinationCannotBe0Address();
if (totalPrincipal > totalUnderlyingMinusSponsored())
revert VaultCannotWithdrawWhenYieldNegative();
_withdrawAll(_to, _ids, false);
}
/// @inheritdoc IVault
function forceWithdraw(address _to, uint256[] calldata _ids)
external
nonReentrant
whenNotExitPaused
{
if (_to == address(0)) revert VaultDestinationCannotBe0Address();
_withdrawAll(_to, _ids, true);
}
function partialWithdraw(
address _to,
uint256[] calldata _ids,
uint256[] calldata _amounts
) external nonReentrant whenNotExitPaused {
if (_to == address(0)) revert VaultDestinationCannotBe0Address();
_withdrawPartial(_to, _ids, _amounts);
}
/// @inheritdoc IVault
function investState()
public
view
override(IVault)
returns (uint256 maxInvestableAmount, uint256 alreadyInvested)
{
if (address(strategy) == address(0)) {
return (0, 0);
}
maxInvestableAmount = totalUnderlying().pctOf(investPct);
alreadyInvested = strategy.investedAssets();
}
/// @inheritdoc IVault
function updateInvested() external override(IVault) onlyKeeper {
if (address(strategy) == address(0)) revert VaultStrategyNotSet();
(uint256 maxInvestableAmount, uint256 alreadyInvested) = investState();
if (maxInvestableAmount == alreadyInvested) revert VaultNothingToDo();
// disinvest
if (alreadyInvested > maxInvestableAmount) {
uint256 disinvestAmount = alreadyInvested - maxInvestableAmount;
if (disinvestAmount < rebalanceMinimum)
revert VaultNotEnoughToRebalance();
uint256 amountWithdrawn = strategy.withdrawToVault(disinvestAmount);
emit Disinvested(amountWithdrawn);
return;
}
// invest
uint256 investAmount = maxInvestableAmount - alreadyInvested;
if (investAmount < rebalanceMinimum) revert VaultNotEnoughToRebalance();
underlying.safeTransfer(address(strategy), investAmount);
strategy.invest();
emit Invested(investAmount);
}
/// @inheritdoc IVault
function withdrawPerformanceFee() external override(IVault) onlyKeeper {
uint256 _perfFee = accumulatedPerfFee;
if (_perfFee == 0) revert VaultNoPerformanceFee();
accumulatedPerfFee = 0;
_rebalanceBeforeWithdrawing(_perfFee);
emit FeeWithdrawn(_perfFee);
underlying.safeTransfer(treasury, _perfFee);
}
//
// IVaultSponsoring
//
/// @inheritdoc IVaultSponsoring
function sponsor(
address _inputToken,
uint256 _amount,
uint256 _lockDuration,
uint256 _slippage
)
external
override(IVaultSponsoring)
nonReentrant
onlySponsor
whenNotPaused
{
if (_amount == 0) revert VaultCannotSponsor0();
if (
_lockDuration < MIN_SPONSOR_LOCK_DURATION ||
_lockDuration > MAX_SPONSOR_LOCK_DURATION
) revert VaultInvalidLockPeriod();
uint256 lockedUntil = _lockDuration + block.timestamp;
_depositTokenIds.increment();
uint256 tokenId = _depositTokenIds.current();
_transferAndCheckInputToken(msg.sender, _inputToken, _amount);
uint256 underlyingAmount = _swapIntoUnderlying(
_inputToken,
_amount,
_slippage
);
deposits[tokenId] = Deposit(
underlyingAmount,
msg.sender,
address(0),
lockedUntil
);
totalSponsored += underlyingAmount;
emit Sponsored(tokenId, underlyingAmount, msg.sender, lockedUntil);
}
/// @inheritdoc IVaultSponsoring
function unsponsor(address _to, uint256[] calldata _ids)
external
nonReentrant
whenNotExitPaused
{
if (_to == address(0)) revert VaultDestinationCannotBe0Address();
_unsponsor(_to, _ids);
}
/// @inheritdoc IVaultSponsoring
function partialUnsponsor(
address _to,
uint256[] calldata _ids,
uint256[] calldata _amounts
) external nonReentrant whenNotExitPaused {
if (_to == address(0)) revert VaultDestinationCannotBe0Address();
_partialUnsponsor(_to, _ids, _amounts);
}
//
// CurveSwapper
//
/// @inheritdoc CurveSwapper
function getUnderlying()
public
view
override(CurveSwapper)
returns (address)
{
return address(underlying);
}
/// Adds a new curve swap pool from an input token to {underlying}
///
/// @param _param Swap pool params
function addPool(SwapPoolParam memory _param) external onlyAdmin {
_addPool(_param);
}
/// Removes an existing swap pool, and the ability to deposit the given token as underlying
///
/// @param _inputToken the token to remove
function removePool(address _inputToken) external onlyAdmin {
_removePool(_inputToken);
}
//
// Admin functions
//
/// @inheritdoc IVaultSettings
function setImmediateInvestLimitPct(uint16 _pct) external onlySettings {
if (!PercentMath.validPct(_pct))
revert VaultInvalidImmediateInvestLimitPct();
emit ImmediateInvestLimitPctUpdated(_pct);
immediateInvestLimitPct = _pct;
}
/// @inheritdoc IVaultSettings
function setInvestPct(uint16 _investPct)
external
override(IVaultSettings)
onlySettings
{
if (!PercentMath.validPct(_investPct)) revert VaultInvalidInvestPct();
emit InvestPctUpdated(_investPct);
investPct = _investPct;
}
/// @inheritdoc IVaultSettings
function setTreasury(address _treasury)
external
override(IVaultSettings)
onlySettings
{
if (address(_treasury) == address(0x0))
revert VaultTreasuryCannotBe0Address();
treasury = _treasury;
emit TreasuryUpdated(_treasury);
}
/// @inheritdoc IVaultSettings
function setPerfFeePct(uint16 _perfFeePct)
external
override(IVaultSettings)
onlySettings
{
if (!PercentMath.validPct(_perfFeePct))
revert VaultInvalidPerformanceFee();
perfFeePct = _perfFeePct;
emit PerfFeePctUpdated(_perfFeePct);
}
/// @inheritdoc IVaultSettings
function setStrategy(address _strategy)
external
override(IVaultSettings)
onlySettings
{
if (_strategy == address(0)) revert VaultStrategyNotSet();
if (IStrategy(_strategy).vault() != address(this))
revert VaultInvalidVault();
if (address(strategy) != address(0) && strategy.hasAssets())
revert VaultStrategyHasInvestedFunds();
strategy = IStrategy(_strategy);
emit StrategyUpdated(_strategy);
}
/// @inheritdoc IVaultSettings
function setLossTolerancePct(uint16 pct)
external
override(IVaultSettings)
onlySettings
{
if (!pct.validPct()) revert VaultInvalidLossTolerance();
lossTolerancePct = pct;
emit LossTolerancePctUpdated(pct);
}
//
// Public API
//
/**
* Computes the total amount of principal + yield currently controlled by the
* vault and the strategy. The principal + yield is the total amount
* of underlying that can be claimed or withdrawn, excluding the sponsored amount and performance fee.
*
* @return Total amount of principal and yield help by the vault (not including sponsored amount and performance fee).
*/
function totalUnderlyingMinusSponsored() public view returns (uint256) {
uint256 _totalUnderlying = totalUnderlying();
uint256 deductAmount = totalSponsored + accumulatedPerfFee;
if (deductAmount > _totalUnderlying) {
return 0;
}
return _totalUnderlying - deductAmount;
}
//
// ERC165
//
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, AccessControl)
returns (bool)
{
return
interfaceId == type(IVault).interfaceId ||
interfaceId == type(IVaultSponsoring).interfaceId ||
super.supportsInterface(interfaceId);
}
//
// Internal API
//
function _immediateInvestment() private {
(uint256 maxInvestableAmount, uint256 alreadyInvested) = investState();
if (
alreadyInvested.inPctOf(maxInvestableAmount) >=
immediateInvestLimitPct
) return;
uint256 investAmount = maxInvestableAmount - alreadyInvested;
if (investAmount < rebalanceMinimum) return;
underlying.safeTransfer(address(strategy), investAmount);
strategy.invest();
emit Invested(investAmount);
}
/**
* Withdraws the principal from the deposits with the ids provided in @param _ids and sends it to @param _to.
*
* @param _to Address that will receive the funds.
* @param _ids Array with the ids of the deposits.
* @param _force Boolean to specify if the action should be perfomed when there's loss.
*/
function _withdrawAll(
address _to,
uint256[] calldata _ids,
bool _force
) internal {
uint256 localTotalShares = totalShares;
uint256 localTotalPrincipal = totalUnderlyingMinusSponsored();
uint256 amount;
uint256 idsLen = _ids.length;
for (uint256 i = 0; i < idsLen; ++i) {
uint256 depositAmount = deposits[_ids[i]].amount;
amount += _withdrawSingle(
_ids[i],
localTotalShares,
localTotalPrincipal,
_to,
_force,
depositAmount
);
}
_rebalanceBeforeWithdrawing(amount);
underlying.safeTransfer(_to, amount);
}
function _withdrawPartial(
address _to,
uint256[] calldata _ids,
uint256[] calldata _amounts
) internal {
uint256 localTotalShares = totalShares;
uint256 localTotalPrincipal = totalUnderlyingMinusSponsored();
uint256 amount;
uint256 idsLen = _ids.length;
for (uint256 i = 0; i < idsLen; ++i) {
amount += _withdrawSingle(
_ids[i],
localTotalShares,
localTotalPrincipal,
_to,
false,
_amounts[i]
);
}
_rebalanceBeforeWithdrawing(amount);
underlying.safeTransfer(_to, amount);
}
/**
* Rebalances the vault's funds to cover the transfer of funds from the vault
* by disinvesting from the strategy. After the rebalance the vault is left
* with a set percentage (100% - invest%) of the total underlying as reserves.
*
* @notice this will have effect only for sync strategies.
*
* @param _amount Funds to be transferred from the vault.
*/
function _rebalanceBeforeWithdrawing(uint256 _amount) internal {
uint256 vaultBalance = underlying.balanceOf(address(this));
if (_amount <= vaultBalance) return;
if (!strategy.isSync()) revert VaultNotEnoughFunds();
uint256 expectedReserves = (totalUnderlying() - _amount).pctOf(
10000 - investPct
);
// we want to withdraw the from the strategy only what is needed
// to cover the transfer and leave the vault with the expected reserves
uint256 needed = _amount + expectedReserves - vaultBalance;
uint256 amountWithdrawn = strategy.withdrawToVault(needed);
emit Disinvested(amountWithdrawn);
}
/**
* Withdraws the sponsored amount for the deposits with the ids provided
* in @param _ids and sends it to @param _to.
*
* @param _to Address that will receive the funds.
* @param _ids Array with the ids of the deposits.
*/
function _unsponsor(address _to, uint256[] calldata _ids) internal {
uint256 sponsorAmount;
uint256 idsLen = _ids.length;
for (uint8 i = 0; i < idsLen; ++i) {
uint256 tokenId = _ids[i];
uint256 amount = deposits[tokenId].amount;
_unsponsorSingle(_to, tokenId, amount);
sponsorAmount += amount;
}
_decreaseTotalSponsoredAndTransfer(_to, sponsorAmount);
}
/**
* Withdraws the specified sponsored amounts @param _amounts for the deposits with the ids provided
* in @param _ids and sends it to @param _to.
*
* @param _to Address that will receive the funds.
* @param _ids Array with the ids of the deposits.
* @param _amounts Array with the amounts to withdraw.
*/
function _partialUnsponsor(
address _to,
uint256[] calldata _ids,
uint256[] calldata _amounts
) internal {
uint256 sponsorAmount;
uint256 idsLen = _ids.length;
for (uint8 i = 0; i < idsLen; ++i) {
uint256 depositId = _ids[i];
uint256 amount = _amounts[i];
_unsponsorSingle(_to, depositId, amount);
sponsorAmount += amount;
}
_decreaseTotalSponsoredAndTransfer(_to, sponsorAmount);
}
/**
* Validates conditions for unsponsoring amount @param _amount of the deposit with the id @param _id.
*
* @param _to Address that will receive the funds.
* @param _tokenId Id of the deposit.
* @param _amount Amount to be unsponsored/withdrawn.
*/
function _unsponsorSingle(
address _to,
uint256 _tokenId,
uint256 _amount
) internal {
Deposit memory _deposit = deposits[_tokenId];
if (_deposit.owner != msg.sender) revert VaultNotAllowed();
if (_deposit.lockedUntil > block.timestamp) revert VaultAmountLocked();
if (_deposit.claimerId != address(0)) revert VaultNotSponsor();
if (_deposit.amount < _amount)
revert VaultCannotWithdrawMoreThanAvailable();
bool isFull = _amount == _deposit.amount;
emit Unsponsored(_tokenId, _amount, _to, isFull);
if (!isFull) {
deposits[_tokenId].amount -= _amount;
return;
}
delete deposits[_tokenId];
}
/**
* Updates totalSponsored by subtracting the amount @param _amount and performing a transfer to @param _to.
*
* @param _to Adress that will receive the funds.
* @param _amount Amount being unsponsored.
*/
function _decreaseTotalSponsoredAndTransfer(address _to, uint256 _amount)
internal
{
if (_amount > totalUnderlying()) revert VaultNotEnoughFunds();
totalSponsored -= _amount;
_rebalanceBeforeWithdrawing(_amount);
underlying.safeTransfer(_to, _amount);
}
/**
* @dev `_createDeposit` declares too many locals
* We move some of them to this struct to fix the problem
*/
struct CreateDepositLocals {
uint256 totalShares;
uint256 totalUnderlying;
uint16 accumulatedPct;
uint256 accumulatedAmount;
uint256 claimsLen;
}
/**
* Creates a deposit with the given amount of underlying and claim
* structure. The deposit is locked until the timestamp specified in @param _lockedUntil.
* @notice This function assumes underlying will be transfered elsewhere in
* the transaction.
*
* @notice Underlying must be transfered *after* this function, in order to
* correctly calculate shares.
*
* @notice claims must add up to 100%.
*
* @param _amount Amount of underlying to consider @param claims claim
* @param _lockedUntil Timestamp at which the deposit unlocks
* @param claims Claim params
* params.
*/
function _createDeposit(
uint256 _previousTotalUnderlying,
uint256 _amount,
uint64 _lockedUntil,
ClaimParams[] calldata claims,
string calldata _name,
uint256 _groupId
) internal returns (uint256[] memory) {
CreateDepositLocals memory locals = CreateDepositLocals({
totalShares: totalShares,
totalUnderlying: _previousTotalUnderlying,
accumulatedPct: 0,
accumulatedAmount: 0,
claimsLen: claims.length
});
uint256[] memory result = new uint256[](locals.claimsLen);
for (uint256 i = 0; i < locals.claimsLen; ++i) {
ClaimParams memory data = claims[i];
if (data.pct == 0) revert VaultClaimPercentageCannotBe0();
if (data.beneficiary == address(0)) revert VaultClaimerCannotBe0();
// if it's the last claim, just grab all remaining amount, instead
// of relying on percentages
uint256 localAmount = i == locals.claimsLen - 1
? _amount - locals.accumulatedAmount
: _amount.pctOf(data.pct);
result[i] = _createClaim(
_groupId,
localAmount,
_lockedUntil,
data,
locals.totalShares,
locals.totalUnderlying,
_name
);
locals.accumulatedPct += data.pct;
locals.accumulatedAmount += localAmount;
}
if (!locals.accumulatedPct.is100Pct()) revert VaultClaimsDontAddUp();
return result;
}
/**
* @dev `_createClaim` declares too many locals