-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathAlchemistV2.sol
1751 lines (1438 loc) · 70.6 KB
/
AlchemistV2.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
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {Unauthorized, IllegalState, IllegalArgument} from "./base/Errors.sol";
import "./base/Multicall.sol";
import "./base/Mutex.sol";
import "./interfaces/IAlchemistV2.sol";
import "./interfaces/IERC20Minimal.sol";
import "./interfaces/IERC20TokenReceiver.sol";
import "./interfaces/ITokenAdapter.sol";
import "./interfaces/IAlchemicToken.sol";
import "./interfaces/IWhitelist.sol";
import "./libraries/SafeCast.sol";
import "./libraries/Sets.sol";
import "./libraries/TokenUtils.sol";
import "./libraries/Limiters.sol";
/// @title AlchemistV2
/// @author Alchemix Finance
contract AlchemistV2 is IAlchemistV2, Initializable, Multicall, Mutex {
using Limiters for Limiters.LinearGrowthLimiter;
using Sets for Sets.AddressSet;
/// @notice A user account.
struct Account {
// A signed value which represents the current amount of debt or credit that the account has accrued.
// Positive values indicate debt, negative values indicate credit.
int256 debt;
// The share balances for each yield token.
mapping(address => uint256) balances;
// The last values recorded for accrued weights for each yield token.
mapping(address => uint256) lastAccruedWeights;
// The set of yield tokens that the account has deposited into the system.
Sets.AddressSet depositedTokens;
// The allowances for mints.
mapping(address => uint256) mintAllowances;
// The allowances for withdrawals.
mapping(address => mapping(address => uint256)) withdrawAllowances;
}
/// @notice The number of basis points there are to represent exactly 100%.
uint256 public constant BPS = 10000;
/// @notice The scalar used for conversion of integral numbers to fixed point numbers. Fixed point numbers in this
/// implementation have 18 decimals of resolution, meaning that 1 is represented as 1e18, 0.5 is
/// represented as 5e17, and 2 is represented as 2e18.
uint256 public constant FIXED_POINT_SCALAR = 1e18;
/// @inheritdoc IAlchemistV2Immutables
string public constant override version = "2.2.6";
/// @inheritdoc IAlchemistV2Immutables
address public override debtToken;
/// @inheritdoc IAlchemistV2State
address public override admin;
/// @inheritdoc IAlchemistV2State
address public override pendingAdmin;
/// @inheritdoc IAlchemistV2State
mapping(address => bool) public override sentinels;
/// @inheritdoc IAlchemistV2State
mapping(address => bool) public override keepers;
/// @inheritdoc IAlchemistV2State
address public override transmuter;
/// @inheritdoc IAlchemistV2State
uint256 public override minimumCollateralization;
/// @inheritdoc IAlchemistV2State
uint256 public override protocolFee;
/// @inheritdoc IAlchemistV2State
address public override protocolFeeReceiver;
/// @inheritdoc IAlchemistV2State
address public override whitelist;
/// @dev A linear growth function that limits the amount of debt-token minted.
Limiters.LinearGrowthLimiter private _mintingLimiter;
// @dev The repay limiters for each underlying token.
mapping(address => Limiters.LinearGrowthLimiter) private _repayLimiters;
// @dev The liquidation limiters for each underlying token.
mapping(address => Limiters.LinearGrowthLimiter) private _liquidationLimiters;
/// @dev Accounts mapped by the address that owns them.
mapping(address => Account) private _accounts;
/// @dev Underlying token parameters mapped by token address.
mapping(address => UnderlyingTokenParams) private _underlyingTokens;
/// @dev Yield token parameters mapped by token address.
mapping(address => YieldTokenParams) private _yieldTokens;
/// @dev An iterable set of the underlying tokens that are supported by the system.
Sets.AddressSet private _supportedUnderlyingTokens;
/// @dev An iterable set of the yield tokens that are supported by the system.
Sets.AddressSet private _supportedYieldTokens;
constructor() initializer {}
/// @inheritdoc IAlchemistV2State
function getYieldTokensPerShare(address yieldToken) external view override returns (uint256) {
return _convertSharesToYieldTokens(yieldToken, 10**_yieldTokens[yieldToken].decimals);
}
/// @inheritdoc IAlchemistV2State
function getUnderlyingTokensPerShare(address yieldToken) external view override returns (uint256) {
return _convertSharesToUnderlyingTokens(yieldToken, 10**_yieldTokens[yieldToken].decimals);
}
/// @inheritdoc IAlchemistV2State
function getSupportedUnderlyingTokens() external view override returns (address[] memory) {
return _supportedUnderlyingTokens.values;
}
/// @inheritdoc IAlchemistV2State
function getSupportedYieldTokens() external view override returns (address[] memory) {
return _supportedYieldTokens.values;
}
/// @inheritdoc IAlchemistV2State
function isSupportedUnderlyingToken(address underlyingToken) external view override returns (bool) {
return _supportedUnderlyingTokens.contains(underlyingToken);
}
/// @inheritdoc IAlchemistV2State
function isSupportedYieldToken(address yieldToken) external view override returns (bool) {
return _supportedYieldTokens.contains(yieldToken);
}
/// @inheritdoc IAlchemistV2State
function accounts(address owner)
external view override
returns (
int256 debt,
address[] memory depositedTokens
)
{
Account storage account = _accounts[owner];
return (
_calculateUnrealizedDebt(owner),
account.depositedTokens.values
);
}
/// @inheritdoc IAlchemistV2State
function positions(address owner, address yieldToken)
external view override
returns (
uint256 shares,
uint256 lastAccruedWeight
)
{
Account storage account = _accounts[owner];
return (account.balances[yieldToken], account.lastAccruedWeights[yieldToken]);
}
/// @inheritdoc IAlchemistV2State
function mintAllowance(address owner, address spender)
external view override
returns (uint256)
{
Account storage account = _accounts[owner];
return account.mintAllowances[spender];
}
/// @inheritdoc IAlchemistV2State
function withdrawAllowance(address owner, address spender, address yieldToken)
external view override
returns (uint256)
{
Account storage account = _accounts[owner];
return account.withdrawAllowances[spender][yieldToken];
}
/// @inheritdoc IAlchemistV2State
function getUnderlyingTokenParameters(address underlyingToken)
external view override
returns (UnderlyingTokenParams memory)
{
return _underlyingTokens[underlyingToken];
}
/// @inheritdoc IAlchemistV2State
function getYieldTokenParameters(address yieldToken)
external view override
returns (YieldTokenParams memory)
{
return _yieldTokens[yieldToken];
}
/// @inheritdoc IAlchemistV2State
function getMintLimitInfo()
external view override
returns (
uint256 currentLimit,
uint256 rate,
uint256 maximum
)
{
return (
_mintingLimiter.get(),
_mintingLimiter.rate,
_mintingLimiter.maximum
);
}
/// @inheritdoc IAlchemistV2State
function getRepayLimitInfo(address underlyingToken)
external view override
returns (
uint256 currentLimit,
uint256 rate,
uint256 maximum
)
{
Limiters.LinearGrowthLimiter storage limiter = _repayLimiters[underlyingToken];
return (
limiter.get(),
limiter.rate,
limiter.maximum
);
}
/// @inheritdoc IAlchemistV2State
function getLiquidationLimitInfo(address underlyingToken)
external view override
returns (
uint256 currentLimit,
uint256 rate,
uint256 maximum
)
{
Limiters.LinearGrowthLimiter storage limiter = _liquidationLimiters[underlyingToken];
return (
limiter.get(),
limiter.rate,
limiter.maximum
);
}
/// @inheritdoc IAlchemistV2AdminActions
function initialize(InitializationParams memory params) external initializer {
_checkArgument(params.protocolFee <= BPS);
debtToken = params.debtToken;
admin = params.admin;
transmuter = params.transmuter;
minimumCollateralization = params.minimumCollateralization;
protocolFee = params.protocolFee;
protocolFeeReceiver = params.protocolFeeReceiver;
whitelist = params.whitelist;
_mintingLimiter = Limiters.createLinearGrowthLimiter(
params.mintingLimitMaximum,
params.mintingLimitBlocks,
params.mintingLimitMinimum
);
emit AdminUpdated(admin);
emit TransmuterUpdated(transmuter);
emit MinimumCollateralizationUpdated(minimumCollateralization);
emit ProtocolFeeUpdated(protocolFee);
emit ProtocolFeeReceiverUpdated(protocolFeeReceiver);
emit MintingLimitUpdated(params.mintingLimitMaximum, params.mintingLimitBlocks);
}
/// @inheritdoc IAlchemistV2AdminActions
function setPendingAdmin(address value) external override {
_onlyAdmin();
pendingAdmin = value;
emit PendingAdminUpdated(value);
}
/// @inheritdoc IAlchemistV2AdminActions
function acceptAdmin() external override {
_checkState(pendingAdmin != address(0));
if (msg.sender != pendingAdmin) {
revert Unauthorized();
}
admin = pendingAdmin;
pendingAdmin = address(0);
emit AdminUpdated(admin);
emit PendingAdminUpdated(address(0));
}
/// @inheritdoc IAlchemistV2AdminActions
function setSentinel(address sentinel, bool flag) external override {
_onlyAdmin();
sentinels[sentinel] = flag;
emit SentinelSet(sentinel, flag);
}
/// @inheritdoc IAlchemistV2AdminActions
function setKeeper(address keeper, bool flag) external override {
_onlyAdmin();
keepers[keeper] = flag;
emit KeeperSet(keeper, flag);
}
/// @inheritdoc IAlchemistV2AdminActions
function addUnderlyingToken(address underlyingToken, UnderlyingTokenConfig calldata config) external override lock {
_onlyAdmin();
_checkState(!_supportedUnderlyingTokens.contains(underlyingToken));
uint8 tokenDecimals = TokenUtils.expectDecimals(underlyingToken);
uint8 debtTokenDecimals = TokenUtils.expectDecimals(debtToken);
_checkArgument(tokenDecimals <= debtTokenDecimals);
_underlyingTokens[underlyingToken] = UnderlyingTokenParams({
decimals: tokenDecimals,
conversionFactor: 10**(debtTokenDecimals - tokenDecimals),
enabled: false
});
_repayLimiters[underlyingToken] = Limiters.createLinearGrowthLimiter(
config.repayLimitMaximum,
config.repayLimitBlocks,
config.repayLimitMinimum
);
_liquidationLimiters[underlyingToken] = Limiters.createLinearGrowthLimiter(
config.liquidationLimitMaximum,
config.liquidationLimitBlocks,
config.liquidationLimitMinimum
);
_supportedUnderlyingTokens.add(underlyingToken);
emit AddUnderlyingToken(underlyingToken);
}
/// @inheritdoc IAlchemistV2AdminActions
function addYieldToken(address yieldToken, YieldTokenConfig calldata config) external override lock {
_onlyAdmin();
_checkArgument(config.maximumLoss <= BPS);
_checkArgument(config.creditUnlockBlocks > 0);
_checkState(!_supportedYieldTokens.contains(yieldToken));
ITokenAdapter adapter = ITokenAdapter(config.adapter);
_checkState(yieldToken == adapter.token());
_checkSupportedUnderlyingToken(adapter.underlyingToken());
_yieldTokens[yieldToken] = YieldTokenParams({
decimals: TokenUtils.expectDecimals(yieldToken),
underlyingToken: adapter.underlyingToken(),
adapter: config.adapter,
maximumLoss: config.maximumLoss,
maximumExpectedValue: config.maximumExpectedValue,
creditUnlockRate: FIXED_POINT_SCALAR / config.creditUnlockBlocks,
activeBalance: 0,
harvestableBalance: 0,
totalShares: 0,
expectedValue: 0,
accruedWeight: 0,
pendingCredit: 0,
distributedCredit: 0,
lastDistributionBlock: 0,
enabled: false
});
_supportedYieldTokens.add(yieldToken);
TokenUtils.safeApprove(yieldToken, config.adapter, type(uint256).max);
TokenUtils.safeApprove(adapter.underlyingToken(), config.adapter, type(uint256).max);
emit AddYieldToken(yieldToken);
emit TokenAdapterUpdated(yieldToken, config.adapter);
emit MaximumLossUpdated(yieldToken, config.maximumLoss);
}
/// @inheritdoc IAlchemistV2AdminActions
function setUnderlyingTokenEnabled(address underlyingToken, bool enabled) external override {
_onlySentinelOrAdmin();
_checkSupportedUnderlyingToken(underlyingToken);
_underlyingTokens[underlyingToken].enabled = enabled;
emit UnderlyingTokenEnabled(underlyingToken, enabled);
}
/// @inheritdoc IAlchemistV2AdminActions
function setYieldTokenEnabled(address yieldToken, bool enabled) external override {
_onlySentinelOrAdmin();
_checkSupportedYieldToken(yieldToken);
_yieldTokens[yieldToken].enabled = enabled;
emit YieldTokenEnabled(yieldToken, enabled);
}
/// @inheritdoc IAlchemistV2AdminActions
function configureRepayLimit(address underlyingToken, uint256 maximum, uint256 blocks) external override {
_onlyAdmin();
_checkSupportedUnderlyingToken(underlyingToken);
_repayLimiters[underlyingToken].update();
_repayLimiters[underlyingToken].configure(maximum, blocks);
emit RepayLimitUpdated(underlyingToken, maximum, blocks);
}
/// @inheritdoc IAlchemistV2AdminActions
function configureLiquidationLimit(address underlyingToken, uint256 maximum, uint256 blocks) external override {
_onlyAdmin();
_checkSupportedUnderlyingToken(underlyingToken);
_liquidationLimiters[underlyingToken].update();
_liquidationLimiters[underlyingToken].configure(maximum, blocks);
emit LiquidationLimitUpdated(underlyingToken, maximum, blocks);
}
/// @inheritdoc IAlchemistV2AdminActions
function setTransmuter(address value) external override {
_onlyAdmin();
_checkArgument(value != address(0));
transmuter = value;
emit TransmuterUpdated(value);
}
/// @inheritdoc IAlchemistV2AdminActions
function setMinimumCollateralization(uint256 value) external override {
_onlyAdmin();
minimumCollateralization = value;
emit MinimumCollateralizationUpdated(value);
}
/// @inheritdoc IAlchemistV2AdminActions
function setProtocolFee(uint256 value) external override {
_onlyAdmin();
_checkArgument(value <= BPS);
protocolFee = value;
emit ProtocolFeeUpdated(value);
}
/// @inheritdoc IAlchemistV2AdminActions
function setProtocolFeeReceiver(address value) external override {
_onlyAdmin();
_checkArgument(value != address(0));
protocolFeeReceiver = value;
emit ProtocolFeeReceiverUpdated(value);
}
/// @inheritdoc IAlchemistV2AdminActions
function configureMintingLimit(uint256 maximum, uint256 rate) external override {
_onlyAdmin();
_mintingLimiter.update();
_mintingLimiter.configure(maximum, rate);
emit MintingLimitUpdated(maximum, rate);
}
/// @inheritdoc IAlchemistV2AdminActions
function configureCreditUnlockRate(address yieldToken, uint256 blocks) external override {
_onlyAdmin();
_checkArgument(blocks > 0);
_checkSupportedYieldToken(yieldToken);
_yieldTokens[yieldToken].creditUnlockRate = FIXED_POINT_SCALAR / blocks;
emit CreditUnlockRateUpdated(yieldToken, blocks);
}
/// @inheritdoc IAlchemistV2AdminActions
function setTokenAdapter(address yieldToken, address adapter) external override {
_onlyAdmin();
_checkState(yieldToken == ITokenAdapter(adapter).token());
_checkSupportedYieldToken(yieldToken);
_yieldTokens[yieldToken].adapter = adapter;
TokenUtils.safeApprove(yieldToken, adapter, type(uint256).max);
TokenUtils.safeApprove(ITokenAdapter(adapter).underlyingToken(), adapter, type(uint256).max);
emit TokenAdapterUpdated(yieldToken, adapter);
}
/// @inheritdoc IAlchemistV2AdminActions
function setMaximumExpectedValue(address yieldToken, uint256 value) external override {
_onlyAdmin();
_checkSupportedYieldToken(yieldToken);
_yieldTokens[yieldToken].maximumExpectedValue = value;
emit MaximumExpectedValueUpdated(yieldToken, value);
}
/// @inheritdoc IAlchemistV2AdminActions
function setMaximumLoss(address yieldToken, uint256 value) external override {
_onlyAdmin();
_checkArgument(value <= BPS);
_checkSupportedYieldToken(yieldToken);
_yieldTokens[yieldToken].maximumLoss = value;
emit MaximumLossUpdated(yieldToken, value);
}
/// @inheritdoc IAlchemistV2AdminActions
function snap(address yieldToken) external override lock {
_onlyAdmin();
_checkSupportedYieldToken(yieldToken);
uint256 expectedValue = _convertYieldTokensToUnderlying(yieldToken, _yieldTokens[yieldToken].activeBalance);
_yieldTokens[yieldToken].expectedValue = expectedValue;
emit Snap(yieldToken, expectedValue);
}
/// @inheritdoc IAlchemistV2AdminActions
function sweepTokens(address rewardToken, uint256 amount) external override lock {
_onlyAdmin();
if (_supportedYieldTokens.contains(rewardToken)) {
revert UnsupportedToken(rewardToken);
}
if (_supportedUnderlyingTokens.contains(rewardToken)) {
revert UnsupportedToken(rewardToken);
}
TokenUtils.safeTransfer(rewardToken, admin, amount);
emit SweepTokens(rewardToken, amount);
}
/// @inheritdoc IAlchemistV2Actions
function approveMint(address spender, uint256 amount) external override {
_onlyWhitelisted();
_approveMint(msg.sender, spender, amount);
}
/// @inheritdoc IAlchemistV2Actions
function approveWithdraw(address spender, address yieldToken, uint256 shares) external override {
_onlyWhitelisted();
_checkSupportedYieldToken(yieldToken);
_approveWithdraw(msg.sender, spender, yieldToken, shares);
}
/// @inheritdoc IAlchemistV2Actions
function poke(address owner) external override lock {
_onlyWhitelisted();
_preemptivelyHarvestDeposited(owner);
_distributeUnlockedCreditDeposited(owner);
_poke(owner);
}
/// @inheritdoc IAlchemistV2Actions
function deposit(
address yieldToken,
uint256 amount,
address recipient
) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(recipient != address(0));
_checkSupportedYieldToken(yieldToken);
// Deposit the yield tokens to the recipient.
uint256 shares = _deposit(yieldToken, amount, recipient);
// Transfer tokens from the message sender now that the internal storage updates have been committed.
TokenUtils.safeTransferFrom(yieldToken, msg.sender, address(this), amount);
return shares;
}
/// @inheritdoc IAlchemistV2Actions
function depositUnderlying(
address yieldToken,
uint256 amount,
address recipient,
uint256 minimumAmountOut
) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(recipient != address(0));
_checkSupportedYieldToken(yieldToken);
// Before depositing, the underlying tokens must be wrapped into yield tokens.
uint256 amountYieldTokens = _wrap(yieldToken, amount, minimumAmountOut);
// Deposit the yield-tokens to the recipient.
return _deposit(yieldToken, amountYieldTokens, recipient);
}
/// @inheritdoc IAlchemistV2Actions
function withdraw(
address yieldToken,
uint256 shares,
address recipient
) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(recipient != address(0));
_checkSupportedYieldToken(yieldToken);
// Withdraw the shares from the system.
uint256 amountYieldTokens = _withdraw(yieldToken, msg.sender, shares, recipient);
// Transfer the yield tokens to the recipient.
TokenUtils.safeTransfer(yieldToken, recipient, amountYieldTokens);
return amountYieldTokens;
}
/// @inheritdoc IAlchemistV2Actions
function withdrawFrom(
address owner,
address yieldToken,
uint256 shares,
address recipient
) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(recipient != address(0));
_checkSupportedYieldToken(yieldToken);
// Preemptively try and decrease the withdrawal allowance. This will save gas when the allowance is not
// sufficient for the withdrawal.
_decreaseWithdrawAllowance(owner, msg.sender, yieldToken, shares);
// Withdraw the shares from the system.
uint256 amountYieldTokens = _withdraw(yieldToken, owner, shares, recipient);
// Transfer the yield tokens to the recipient.
TokenUtils.safeTransfer(yieldToken, recipient, amountYieldTokens);
return amountYieldTokens;
}
/// @inheritdoc IAlchemistV2Actions
function withdrawUnderlying(
address yieldToken,
uint256 shares,
address recipient,
uint256 minimumAmountOut
) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(recipient != address(0));
_checkSupportedYieldToken(yieldToken);
_checkLoss(yieldToken);
uint256 amountYieldTokens = _withdraw(yieldToken, msg.sender, shares, recipient);
return _unwrap(yieldToken, amountYieldTokens, recipient, minimumAmountOut);
}
/// @inheritdoc IAlchemistV2Actions
function withdrawUnderlyingFrom(
address owner,
address yieldToken,
uint256 shares,
address recipient,
uint256 minimumAmountOut
) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(recipient != address(0));
_checkSupportedYieldToken(yieldToken);
_checkLoss(yieldToken);
_decreaseWithdrawAllowance(owner, msg.sender, yieldToken, shares);
uint256 amountYieldTokens = _withdraw(yieldToken, owner, shares, recipient);
return _unwrap(yieldToken, amountYieldTokens, recipient, minimumAmountOut);
}
/// @inheritdoc IAlchemistV2Actions
function mint(uint256 amount, address recipient) external override lock {
_onlyWhitelisted();
_checkArgument(amount > 0);
_checkArgument(recipient != address(0));
// Mint tokens from the message sender's account to the recipient.
_mint(msg.sender, amount, recipient);
}
/// @inheritdoc IAlchemistV2Actions
function mintFrom(
address owner,
uint256 amount,
address recipient
) external override lock {
_onlyWhitelisted();
_checkArgument(amount > 0);
_checkArgument(recipient != address(0));
// Preemptively try and decrease the minting allowance. This will save gas when the allowance is not sufficient
// for the mint.
_decreaseMintAllowance(owner, msg.sender, amount);
// Mint tokens from the owner's account to the recipient.
_mint(owner, amount, recipient);
}
/// @inheritdoc IAlchemistV2Actions
function burn(uint256 amount, address recipient) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(amount > 0);
_checkArgument(recipient != address(0));
// Distribute unlocked credit to depositors.
_distributeUnlockedCreditDeposited(recipient);
// Update the recipient's account, decrease the debt of the recipient by the number of tokens burned.
_poke(recipient);
// Check that the debt is greater than zero.
//
// It is possible that the number of debt which is repayable is equal to or less than zero after realizing the
// credit that was earned since the last update. We do not want to perform a noop so we need to check that the
// amount of debt to repay is greater than zero.
int256 debt;
_checkState((debt = _accounts[recipient].debt) > 0);
// Limit how much debt can be repaid up to the current amount of debt that the account has. This prevents
// situations where the user may be trying to repay their entire debt, but it decreases since they send the
// transaction and causes a revert because burning can never decrease the debt below zero.
//
// Casts here are safe because it is asserted that debt is greater than zero.
uint256 credit = amount > uint256(debt) ? uint256(debt) : amount;
// Update the recipient's debt.
_updateDebt(recipient, -SafeCast.toInt256(credit));
// Burn the tokens from the message sender.
TokenUtils.safeBurnFrom(debtToken, msg.sender, credit);
emit Burn(msg.sender, credit, recipient);
return credit;
}
/// @inheritdoc IAlchemistV2Actions
function repay(address underlyingToken, uint256 amount, address recipient) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(amount > 0);
_checkArgument(recipient != address(0));
_checkSupportedUnderlyingToken(underlyingToken);
_checkUnderlyingTokenEnabled(underlyingToken);
// Distribute unlocked credit to depositors.
_distributeUnlockedCreditDeposited(recipient);
// Update the recipient's account and decrease the amount of debt incurred.
_poke(recipient);
// Check that the debt is greater than zero.
//
// It is possible that the amount of debt which is repayable is equal to or less than zero after realizing the
// credit that was earned since the last update. We do not want to perform a noop so we need to check that the
// amount of debt to repay is greater than zero.
int256 debt;
_checkState((debt = _accounts[recipient].debt) > 0);
// Determine the maximum amount of underlying tokens that can be repaid.
//
// It is implied that this value is greater than zero because `debt` is greater than zero so a noop is not possible
// beyond this point. Casting the debt to an unsigned integer is also safe because `debt` is greater than zero.
uint256 maximumAmount = _normalizeDebtTokensToUnderlying(underlyingToken, uint256(debt));
// Limit the number of underlying tokens to repay up to the maximum allowed.
uint256 actualAmount = amount > maximumAmount ? maximumAmount : amount;
Limiters.LinearGrowthLimiter storage limiter = _repayLimiters[underlyingToken];
// Check to make sure that the underlying token repay limit has not been breached.
uint256 currentRepayLimit = limiter.get();
if (actualAmount > currentRepayLimit) {
revert RepayLimitExceeded(underlyingToken, actualAmount, currentRepayLimit);
}
uint256 credit = _normalizeUnderlyingTokensToDebt(underlyingToken, actualAmount);
// Update the recipient's debt.
_updateDebt(recipient, -SafeCast.toInt256(credit));
// Decrease the amount of the underlying token which is globally available to be repaid.
limiter.decrease(actualAmount);
// Transfer the repaid tokens to the transmuter.
TokenUtils.safeTransferFrom(underlyingToken, msg.sender, transmuter, actualAmount);
// Inform the transmuter that it has received tokens.
IERC20TokenReceiver(transmuter).onERC20Received(underlyingToken, actualAmount);
emit Repay(msg.sender, underlyingToken, actualAmount, recipient);
return actualAmount;
}
/// @inheritdoc IAlchemistV2Actions
function liquidate(
address yieldToken,
uint256 shares,
uint256 minimumAmountOut
) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(shares > 0);
YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];
address underlyingToken = yieldTokenParams.underlyingToken;
_checkSupportedYieldToken(yieldToken);
_checkYieldTokenEnabled(yieldToken);
_checkUnderlyingTokenEnabled(underlyingToken);
_checkLoss(yieldToken);
// Calculate the unrealized debt.
//
// It is possible that the number of debt which is repayable is equal to or less than zero after realizing the
// credit that was earned since the last update. We do not want to perform a noop so we need to check that the
// amount of debt to repay is greater than zero.
int256 unrealizedDebt;
_checkState((unrealizedDebt = _calculateUnrealizedDebt(msg.sender)) > 0);
// Determine the maximum amount of shares that can be liquidated from the unrealized debt.
//
// It is implied that this value is greater than zero because `debt` is greater than zero. Casting the debt to an
// unsigned integer is also safe for this reason.
uint256 maximumShares = _convertUnderlyingTokensToShares(
yieldToken,
_normalizeDebtTokensToUnderlying(underlyingToken, uint256(unrealizedDebt))
);
// Limit the number of shares to liquidate up to the maximum allowed.
uint256 actualShares = shares > maximumShares ? maximumShares : shares;
// Unwrap the yield tokens that the shares are worth.
uint256 amountYieldTokens = _convertSharesToYieldTokens(yieldToken, actualShares);
uint256 amountUnderlyingTokens = _unwrap(yieldToken, amountYieldTokens, address(this), minimumAmountOut);
// Again, perform another noop check. It is possible that the amount of underlying tokens that were received by
// unwrapping the yield tokens was zero because the amount of yield tokens to unwrap was too small.
_checkState(amountUnderlyingTokens > 0);
Limiters.LinearGrowthLimiter storage limiter = _liquidationLimiters[underlyingToken];
// Check to make sure that the underlying token liquidation limit has not been breached.
uint256 liquidationLimit = limiter.get();
if (amountUnderlyingTokens > liquidationLimit) {
revert LiquidationLimitExceeded(underlyingToken, amountUnderlyingTokens, liquidationLimit);
}
// Buffers any harvestable yield tokens. This will properly synchronize the balance which is held by users
// and the balance which is held by the system. This is required for `_sync` to function correctly.
_preemptivelyHarvest(yieldToken);
// Distribute unlocked credit to depositors.
_distributeUnlockedCreditDeposited(msg.sender);
uint256 credit = _normalizeUnderlyingTokensToDebt(underlyingToken, amountUnderlyingTokens);
// Update the message sender's account, proactively burn shares, decrease the amount of debt incurred, and then
// decrease the value of the token that the system is expected to hold.
_poke(msg.sender, yieldToken);
_burnShares(msg.sender, yieldToken, actualShares);
_updateDebt(msg.sender, -SafeCast.toInt256(credit));
_sync(yieldToken, amountYieldTokens, _usub);
// Decrease the amount of the underlying token which is globally available to be liquidated.
limiter.decrease(amountUnderlyingTokens);
// Transfer the liquidated tokens to the transmuter.
TokenUtils.safeTransfer(underlyingToken, transmuter, amountUnderlyingTokens);
// Inform the transmuter that it has received tokens.
IERC20TokenReceiver(transmuter).onERC20Received(underlyingToken, amountUnderlyingTokens);
emit Liquidate(msg.sender, yieldToken, underlyingToken, actualShares);
return actualShares;
}
/// @inheritdoc IAlchemistV2Actions
function donate(address yieldToken, uint256 amount) external override lock {
_onlyWhitelisted();
_checkArgument(amount != 0);
// Distribute any unlocked credit so that the accrued weight is up to date.
_distributeUnlockedCredit(yieldToken);
// Update the message sender's account. This will assure that any credit that was earned is not overridden.
_poke(msg.sender);
uint256 shares = _yieldTokens[yieldToken].totalShares - _accounts[msg.sender].balances[yieldToken];
_yieldTokens[yieldToken].accruedWeight += amount * FIXED_POINT_SCALAR / shares;
_accounts[msg.sender].lastAccruedWeights[yieldToken] = _yieldTokens[yieldToken].accruedWeight;
TokenUtils.safeBurnFrom(debtToken, msg.sender, amount);
emit Donate(msg.sender, yieldToken, amount);
}
/// @inheritdoc IAlchemistV2Actions
function harvest(address yieldToken, uint256 minimumAmountOut) external override lock {
_onlyKeeper();
_checkSupportedYieldToken(yieldToken);
YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];
// Buffer any harvestable yield tokens. This will properly synchronize the balance which is held by users
// and the balance which is held by the system to be harvested during this call.
_preemptivelyHarvest(yieldToken);
// Load and proactively clear the amount of harvestable tokens so that future calls do not rely on stale data.
// Because we cannot call an external unwrap until the amount of harvestable tokens has been calculated,
// clearing this data immediately prevents any potential reentrancy attacks which would use stale harvest
// buffer values.
uint256 harvestableAmount = yieldTokenParams.harvestableBalance;
yieldTokenParams.harvestableBalance = 0;
// Check that the harvest will not be a no-op.
_checkState(harvestableAmount != 0);
address underlyingToken = yieldTokenParams.underlyingToken;
uint256 amountUnderlyingTokens = _unwrap(yieldToken, harvestableAmount, address(this), minimumAmountOut);
// Calculate how much of the unwrapped underlying tokens will be allocated for fees and distributed to users.
uint256 feeAmount = amountUnderlyingTokens * protocolFee / BPS;
uint256 distributeAmount = amountUnderlyingTokens - feeAmount;
uint256 credit = _normalizeUnderlyingTokensToDebt(underlyingToken, distributeAmount);
// Distribute credit to all of the users who hold shares of the yield token.
_distributeCredit(yieldToken, credit);
// Transfer the tokens to the fee receiver and transmuter.
TokenUtils.safeTransfer(underlyingToken, protocolFeeReceiver, feeAmount);
TokenUtils.safeTransfer(underlyingToken, transmuter, distributeAmount);
// Inform the transmuter that it has received tokens.
IERC20TokenReceiver(transmuter).onERC20Received(underlyingToken, distributeAmount);
emit Harvest(yieldToken, minimumAmountOut, amountUnderlyingTokens);
}
/// @dev Checks that the `msg.sender` is the administrator.
///
/// @dev `msg.sender` must be the administrator or this call will revert with an {Unauthorized} error.
function _onlyAdmin() internal view {
if (msg.sender != admin) {
revert Unauthorized();
}
}
/// @dev Checks that the `msg.sender` is the administrator or a sentinel.
///
/// @dev `msg.sender` must be either the administrator or a sentinel or this call will revert with an
/// {Unauthorized} error.
function _onlySentinelOrAdmin() internal view {
// Check if the message sender is the administrator.
if (msg.sender == admin) {
return;
}
// Check if the message sender is a sentinel. After this check we can revert since we know that it is neither
// the administrator or a sentinel.
if (!sentinels[msg.sender]) {
revert Unauthorized();
}
}
/// @dev Checks that the `msg.sender` is a keeper.
///
/// @dev `msg.sender` must be a keeper or this call will revert with an {Unauthorized} error.
function _onlyKeeper() internal view {
if (!keepers[msg.sender]) {
revert Unauthorized();
}
}
/// @dev Preemptively harvests all of the yield tokens that have been deposited into an account.
///
/// @param owner The address which owns the account.
function _preemptivelyHarvestDeposited(address owner) internal {
Sets.AddressSet storage depositedTokens = _accounts[owner].depositedTokens;
for (uint256 i = 0; i < depositedTokens.values.length; i++) {
_preemptivelyHarvest(depositedTokens.values[i]);
}
}
/// @dev Preemptively harvests `yieldToken`.
///
/// @dev This will earmark yield tokens to be harvested at a future time when the current value of the token is
/// greater than the expected value. The purpose of this function is to synchronize the balance of the yield
/// token which is held by users versus tokens which will be seized by the protocol.
///