-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathTargetFunctions.sol
More file actions
954 lines (835 loc) · 39.7 KB
/
Copy pathTargetFunctions.sol
File metadata and controls
954 lines (835 loc) · 39.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
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
// SPDX-License-Identifier: MIT
pragma solidity 0.8.23;
// Test imports
import {Setup} from "./Setup.sol";
import {console} from "forge-std/console.sol";
import {StdUtils} from "forge-std/StdUtils.sol";
import {StdStyle} from "forge-std/StdStyle.sol";
// Solmate
import {MockERC20} from "@solmate/test/utils/mocks/MockERC20.sol";
// Contracts
import {IERC20} from "contracts/Interfaces.sol";
import {IERC4626} from "contracts/Interfaces.sol";
import {UserCooldown} from "contracts/Interfaces.sol";
// Helpers
import {Find} from "./helpers/Find.sol";
import {Math} from "./helpers/Math.sol";
/// @title TargetFunctions
/// @notice TargetFunctions contract for tests, containing the target functions that should be tested.
/// This is the entry point with the contract we are testing. Ideally, it should never revert.
/// @dev Target parameters use full ABI words so corpus mutations remain decodable in strict mode. Handlers
/// derive booleans and bound narrower values internally.
abstract contract TargetFunctions is Setup, StdUtils {
// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║ ✦✦✦ ETHENA ARM ✦✦✦ ║
// ╚══════════════════════════════════════════════════════════════════════════════╝
// [x] SwapExactTokensForTokens
// [x] SwapTokensForExactTokens
// [x] Deposit
// [x] Allocate
// [x] CollectFees
// [x] RequestRedeem
// [x] ClaimRedeem
// [x] RequestBaseWithdrawal
// [x] ClaimBaseWithdrawals
// --- Admin functions
// [x] SetPrices
// [x] SetCrossPrice
// [x] SetFee
// [x] SetActiveMarket
// [x] SetARMBuffer
//
// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║ ✦✦✦ SUSDE ✦✦✦ ║
// ╚══════════════════════════════════════════════════════════════════════════════╝
// [x] Deposit
// [x] CoolDownShares
// [x] Unstake
// --- Admin functions
// [x] TransferInRewards
//
// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║ ✦✦✦ MORPHO ✦✦✦ ║
// ╚══════════════════════════════════════════════════════════════════════════════╝
// [x] Deposit
// [x] Withdraw
// [x] TransferInRewards
// [x] SetUtilizationRate
//
// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║ ✦✦✦ ✦✦✦ ║
// ╚══════════════════════════════════════════════════════════════════════════════╝
// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║ ✦✦✦ ETHENA ARM ✦✦✦ ║
// ╚══════════════════════════════════════════════════════════════════════════════╝
function _buyPrice() internal view returns (uint256 buyPrice) {
(uint128 buyPriceMem,,,,,,,,) = arm.baseAssetConfigs(address(susde));
buyPrice = buyPriceMem;
}
function _sellPrice() internal view returns (uint256 sellPrice) {
(, uint128 sellPriceMem,,,,,,,) = arm.baseAssetConfigs(address(susde));
sellPrice = sellPriceMem;
}
function _crossPrice() internal view returns (uint256 crossPrice) {
(,,,, uint128 crossPriceMem,,,,) = arm.baseAssetConfigs(address(susde));
crossPrice = crossPriceMem;
}
function targetARMDeposit(uint256 amount, uint256 randomAddressIndex) external ensureExchangeRateIncrease {
// Mirror AbstractARM._deposit's Insolvent() guard: at the asset floor, deposits are allowed
// only before any live LP shares exist and when there are no senior liabilities.
bool initialDeposit = arm.totalSupply() == DEFAULT_MIN_TOTAL_SUPPLY;
if (assume(
arm.totalAssets() > 1e12
|| (initialDeposit && arm.feesAccrued() == 0 && arm.reservedWithdrawLiquidity() == 0)
)) {
return;
}
// Select a random user from makers
address user = makers[randomAddressIndex % MAKERS_COUNT];
uint256 totalSupply = arm.totalSupply();
uint256 totalAssets = arm.totalAssets();
// Min amount to avoid 0 shares minting
uint256 minAmount = totalAssets / totalSupply + 1;
amount = _bound(amount, minAmount, type(uint88).max);
// Mint amount to user
MockERC20(address(usde)).mint(user, amount);
// Deposit as user
vm.prank(user);
uint256 shares = arm.deposit(amount, user);
if (isConsoleAvailable) {
console.log(
">>> ARM Deposit:\t %s deposited %18e USDe\t and received %18e ARM shares",
vm.getLabel(user),
amount,
shares
);
}
sumUSDeUserDeposit += amount;
mintedUSDe[user] += amount;
}
function targetARMRequestRedeem(uint256 shareAmount, uint256) external ensureExchangeRateIncrease {
address user;
uint256 balance;
(user, balance) = Find.getUserWithARMShares(makers, address(arm));
if (assume(user != address(0))) return;
// Bound shareAmount to [1, balance]
shareAmount = _bound(shareAmount, 1, balance);
// Request redeem as user
vm.prank(user);
(uint256 requestId, uint256 amount) = arm.requestRedeem(shareAmount);
pendingRequests[user].push(requestId);
if (isConsoleAvailable) {
console.log(
string(
abi.encodePacked(
">>> ARM Request:\t ",
vm.getLabel(user),
" requested redeem of %18e ARM shares\t for %18e USDe underlying\t Request ID: %d"
)
),
shareAmount,
amount,
requestId
);
}
sumUSDeUserRequest += amount;
sumARMUserRequestShares += shareAmount;
}
function targetARMClaimRedeem(uint256 randomAddressIndex, uint256 randomArrayIndex)
external
ensureExchangeRateIncrease
ensureTimeIncrease
{
address user;
uint256 requestId;
uint256 claimTimestamp;
uint256 claimable = arm.claimable();
uint256 availableLiquidity = usde.balanceOf(address(arm));
address market = arm.activeMarket();
if (market != address(0)) {
availableLiquidity += IERC4626(market).maxWithdraw(address(arm));
}
if (assume(claimable != 0)) return;
// Find a user with a pending request, where the amount is <= claimable
{
(user, requestId, claimTimestamp) = Find.getUserRequestWithAmount(
Find.GetUserRequestWithAmountStruct({
arm: address(arm),
randomAddressIndex: uint248(randomAddressIndex),
randomArrayIndex: uint248(randomArrayIndex),
users: makers,
claimable: uint128(claimable),
availableLiquidity: uint128(availableLiquidity)
}),
pendingRequests
);
if (assume(user != address(0))) return;
}
// Fast forward time if needed
if (block.timestamp < claimTimestamp) {
if (isConsoleAvailable) {
console.log(
StdStyle.yellow(
string(
abi.encodePacked(
">>> Time jump:\t Fast forwarded to: ",
vm.toString(claimTimestamp),
" (+ ",
vm.toString(claimTimestamp - block.timestamp),
"s)"
)
)
)
);
}
vm.warp(claimTimestamp);
}
// Claim redeem as user
uint256 balanceBefore = usde.balanceOf(address(arm));
uint256 requestShares = arm.withdrawalRequestShares(requestId);
vm.prank(user);
uint256 amount = arm.claimRedeem(requestId);
if (isConsoleAvailable) {
console.log(
string(
abi.encodePacked(
">>> ARM Claim:\t ",
vm.getLabel(user),
" claimed redeem request ID %d\t and received %18e USDe underlying"
)
),
requestId,
amount
);
}
sumUSDeUserRedeem += amount;
sumARMUserRedeemShares += requestShares;
if (balanceBefore < amount) {
// This means we had to withdraw from market
sumUSDeMarketWithdraw += amount - balanceBefore;
}
}
function targetARMSetARMBuffer(uint256 pct) external ensureExchangeRateIncrease {
pct = _bound(pct, 0, 100);
vm.prank(operator);
arm.setARMBuffer(pct * 1e16);
if (isConsoleAvailable) {
console.log(">>> ARM Buffer:\t Governor set ARM buffer to %s%", pct);
}
}
function targetARMSetActiveMarket(uint256 activeSeed) external ensureExchangeRateIncrease {
bool isActive = activeSeed % 2 == 0;
// If isActive is true it will `setActiveMarket` with MorphoMarket
// else it will set it to address(0)
address currentMarket = arm.activeMarket();
address targetMarket = isActive ? address(market) : address(0);
// If the current market is the morpho market and we want to deactivate it
// ensure the is enough liquidity in Morpho to cover the ARM's assets withdrawals
if (currentMarket == address(market) && !isActive) {
uint256 shares = market.balanceOf(address(arm));
uint256 assets = market.convertToAssets(shares);
uint256 availableLiquidity = morpho.availableLiquidity();
if (assume(assets < availableLiquidity)) return;
}
uint256 balanceBefore = usde.balanceOf(address(arm));
vm.prank(operator);
arm.setActiveMarket(targetMarket);
uint256 balanceAfter = usde.balanceOf(address(arm));
if (isConsoleAvailable) {
console.log(
">>> ARM SetMarket:\t Governor set active market to %s", isActive ? "Morpho Market" : "No active market"
);
}
int256 diff = int256(balanceAfter) - int256(balanceBefore);
if (diff > 0) {
sumUSDeMarketWithdraw += uint256(diff);
} else {
sumUSDeMarketDeposit += uint256(-diff);
}
}
function targetARMAllocate() external ensureExchangeRateIncrease {
address currentMarket = arm.activeMarket();
if (assume(currentMarket != address(0))) return;
(int256 targetLiquidityDelta, int256 actualLiquidityDelta) = arm.allocate();
if (isConsoleAvailable) {
console.log(
string(
abi.encodePacked(
">>> ARM Allocate:\t ARM allocated liquidity to active market. Target delta: ",
targetLiquidityDelta < 0 ? "-" : "",
"%18e USDe\t Actual delta: ",
actualLiquidityDelta < 0 ? "-" : "",
"%18e USDe"
)
),
Math.abs(targetLiquidityDelta),
Math.abs(actualLiquidityDelta)
);
}
if (actualLiquidityDelta > 0) {
sumUSDeMarketDeposit += uint256(actualLiquidityDelta);
} else {
sumUSDeMarketWithdraw += uint256(-actualLiquidityDelta);
}
}
function targetARMSetPrices(uint256 buyPrice, uint256 sellPrice) external ensureExchangeRateIncrease {
uint256 crossPrice = _crossPrice();
// Bound sellPrice
sellPrice = uint120(_bound(sellPrice, crossPrice, (1e37 - 1) / 9)); // -> min traderate0 -> 0.9e36
// Bound buyPrice
buyPrice = uint120(_bound(buyPrice, 0.9e36, crossPrice - 1)); // -> min traderate1 -> 0.9e36
vm.prank(operator);
arm.setPrices(address(susde), buyPrice, sellPrice, type(uint128).max, type(uint128).max);
if (isConsoleAvailable) {
console.log(
">>> ARM SetPrices:\t Governor set buy price to %36e\t sell price to %36e\t cross price to %36e",
buyPrice,
1e72 / sellPrice,
_crossPrice()
);
}
}
function targetARMSetCrossPrice(uint256 crossPrice) external ensureExchangeRateIncrease {
uint256 maxCrossPrice = 1e36;
uint256 minCrossPrice = 1e36 - 20e32;
uint256 sellT1 = _sellPrice();
uint256 buyT1 = _buyPrice() + 1;
minCrossPrice = Math.max(minCrossPrice, buyT1);
maxCrossPrice = Math.min(maxCrossPrice, sellT1);
if (assume(maxCrossPrice >= minCrossPrice)) return;
crossPrice = _bound(crossPrice, minCrossPrice, maxCrossPrice);
uint256 susdeBalance = susde.balanceOf(address(arm));
(,,,,, uint128 pendingRedeemAssets,,,) = arm.baseAssetConfigs(address(susde));
bool loweringCrossPrice = _crossPrice() > crossPrice;
if (loweringCrossPrice && assume(uint256(pendingRedeemAssets) < DEFAULT_MIN_TOTAL_SUPPLY)) return;
if (loweringCrossPrice && susdeBalance > 0) {
// If there is more than 100 susde in ARM, do nothing
if (assume(susde.convertToAssets(susdeBalance) + uint256(pendingRedeemAssets) < 1e20)) return;
// If there is less than 100 susde in ARM, swap them all to usde, to avoid creating loss on ARM
// Mint too much USDe to be sure we can swap all sUSDe in ARM
if (susdeBalance > 0) {
MockERC20(address(usde)).mint(address(this), susde.convertToAssets(susdeBalance) * 10);
usde.approve(address(arm), type(uint256).max);
uint256[] memory obtained = arm.swapTokensForExactTokens(
IERC20(address(usde)), IERC20(address(susde)), susdeBalance, type(uint256).max, address(this)
);
if (isConsoleAvailable) {
console.log(
string(
abi.encodePacked(
">>> ARM SetCPrice:\t ",
vm.getLabel(address(this)),
" swapped %18e USDe\t for %18e sUSDe\t to adjust cross price"
)
),
obtained[0],
obtained[1]
);
}
require(susde.balanceOf(address(arm)) < 10, "ARM still has too much sUSDe after swap");
sumUSDeSwapIn += obtained[0];
sumSUSDeSwapOut += obtained[1];
}
}
if (
loweringCrossPrice
&& assume(susde.balanceOf(address(arm)) + uint256(pendingRedeemAssets) < DEFAULT_MIN_TOTAL_SUPPLY)
) {
return;
}
vm.prank(governor);
arm.setCrossPrice(address(susde), crossPrice);
if (isConsoleAvailable) {
console.log(">>> ARM SetCPrice:\t Governor set cross price to %36e", crossPrice);
}
}
function targetARMSwapExactTokensForTokens(uint256 sideSeed, uint256 amountIn, uint256 randomAddressIndex)
external
ensureExchangeRateIncrease
{
bool token0ForToken1 = sideSeed % 2 == 0;
(IERC20 tokenIn, IERC20 tokenOut) = token0ForToken1
? (IERC20(address(usde)), IERC20(address(susde)))
: (IERC20(address(susde)), IERC20(address(usde)));
// What's the maximum amountOut we can obtain?
uint256 maxAmountOut;
if (address(tokenOut) == address(usde)) {
uint256 balance = usde.balanceOf(address(arm));
uint256 outstandingWithdrawals = arm.reservedWithdrawLiquidity();
maxAmountOut = outstandingWithdrawals >= balance ? 0 : balance - outstandingWithdrawals;
} else {
maxAmountOut = susde.balanceOf(address(arm));
}
// Ensure there is liquidity available in ARM
if (assume(maxAmountOut > 1)) return;
// What's the maximum amountIn we can provide to not exceed maxAmountOut?
uint256 maxAmountIn = token0ForToken1
? (maxAmountOut * _sellPrice() / 1e36) * susde.totalAssets() / susde.totalSupply()
: (maxAmountOut * 1e36 / _buyPrice()) * susde.totalSupply() / susde.totalAssets();
if (assume(maxAmountIn > 0)) return;
// Bound amountIn
amountIn = _bound(amountIn, 1, Math.min(maxAmountIn, type(uint88).max));
// Select a random user from makers
address user = traders[randomAddressIndex % TRADERS_COUNT];
vm.startPrank(user);
// Mint amountIn to user
if (token0ForToken1) {
MockERC20(address(usde)).mint(user, amountIn);
} else {
// Mint too much USDe to user to be able to mint enough sUSDe
MockERC20(address(usde)).mint(user, uint256(amountIn) * 10);
// Mint sUSDe to user
susde.mint(amountIn, user);
// Burn excess USDe
MockERC20(address(usde)).burn(user, usde.balanceOf(user));
}
// Perform swap
uint256[] memory obtained = arm.swapExactTokensForTokens(tokenIn, tokenOut, amountIn, 0, user);
vm.stopPrank();
if (isConsoleAvailable) {
console.log(
string(
abi.encodePacked(
">>> ARM SwapEF:\t ",
vm.getLabel(user),
" swapped %18e ",
token0ForToken1 ? "USDe" : "sUSDe",
"\t for %18e ",
token0ForToken1 ? "sUSDe" : "USDe"
)
),
amountIn,
obtained[1]
);
}
require(obtained[0] == amountIn, "Amount in mismatch");
if (token0ForToken1) {
sumUSDeSwapIn += obtained[0];
sumSUSDeSwapOut += obtained[1];
} else {
sumSUSDeSwapIn += obtained[0];
sumUSDeSwapOut += obtained[1];
}
}
function targetARMSwapTokensForExactTokens(uint256 sideSeed, uint256 amountOut, uint256 randomAddressIndex)
external
ensureExchangeRateIncrease
{
bool token0ForToken1 = sideSeed % 2 == 0;
(IERC20 tokenIn, IERC20 tokenOut) = token0ForToken1
? (IERC20(address(usde)), IERC20(address(susde)))
: (IERC20(address(susde)), IERC20(address(usde)));
// What's the maximum amountOut we can obtain?
uint256 maxAmountOut;
if (address(tokenOut) == address(usde)) {
uint256 balance = usde.balanceOf(address(arm));
uint256 outstandingWithdrawals = arm.reservedWithdrawLiquidity();
maxAmountOut = outstandingWithdrawals >= balance ? 0 : balance - outstandingWithdrawals;
} else {
maxAmountOut = susde.balanceOf(address(arm));
}
// Ensure there is liquidity available in ARM
if (assume(maxAmountOut > 1)) return;
amountOut = _bound(amountOut, 1, Math.min(maxAmountOut, type(uint88).max));
// What's the maximum amountIn we can provide to not exceed maxAmountOut?
uint256 convertedAmountOut;
if (token0ForToken1) {
convertedAmountOut = (amountOut * susde.totalAssets()) / susde.totalSupply();
} else {
convertedAmountOut = (amountOut * susde.totalSupply()) / susde.totalAssets();
}
uint256 amountIn = token0ForToken1
? (uint256(convertedAmountOut) * _sellPrice() / 1e36) + 3 + 10
: ((uint256(convertedAmountOut) * 1e36) / _buyPrice()) + 3 + 10; // slippage + rounding buffer
// Select a random user from makers
address user = traders[randomAddressIndex % TRADERS_COUNT];
vm.startPrank(user);
// Mint amountIn to user
if (token0ForToken1) {
MockERC20(address(usde)).mint(user, amountIn);
} else {
// Mint too much USDe to user to be able to mint enough sUSDe
MockERC20(address(usde)).mint(user, amountIn * 2);
// Mint sUSDe to user
susde.mint(amountIn, user);
// Burn excess USDe
MockERC20(address(usde)).burn(user, usde.balanceOf(user));
}
// Perform swap
uint256[] memory obtained = arm.swapTokensForExactTokens(tokenIn, tokenOut, amountOut, type(uint256).max, user);
vm.stopPrank();
if (isConsoleAvailable) {
console.log(
string(
abi.encodePacked(
">>> ARM SwapFT:\t ",
vm.getLabel(user),
" swapped %18e ",
token0ForToken1 ? "USDe" : "sUSDe",
"\t for %18e ",
token0ForToken1 ? "sUSDe" : "USDe"
)
),
obtained[0],
amountOut
);
}
require(obtained[1] == amountOut, "Amount out mismatch");
if (token0ForToken1) {
sumUSDeSwapIn += obtained[0];
sumSUSDeSwapOut += obtained[1];
} else {
sumSUSDeSwapIn += obtained[0];
sumUSDeSwapOut += obtained[1];
}
}
function targetARMCollectFees() external ensureExchangeRateIncrease {
uint256 feesAccrued = arm.feesAccrued();
uint256 balance = usde.balanceOf(address(arm));
uint256 outstandingWithdrawals = arm.reservedWithdrawLiquidity();
if (assume(balance >= feesAccrued + outstandingWithdrawals)) return;
uint256 feesCollected = arm.collectFees();
if (isConsoleAvailable) {
console.log(">>> ARM Collect:\t Governor collected %18e USDe in fees", feesCollected);
}
require(feesCollected == feesAccrued, "Fees collected mismatch");
sumUSDeFeesCollected += feesCollected;
}
function targetARMSetFees(uint256 fee) external ensureExchangeRateIncrease {
// Ensure current fee can be collected
uint256 feesAccrued = arm.feesAccrued();
if (feesAccrued != 0) {
uint256 balance = usde.balanceOf(address(arm));
uint256 outstandingWithdrawals = arm.reservedWithdrawLiquidity();
if (assume(balance >= feesAccrued + outstandingWithdrawals)) return;
}
uint256 oldFee = arm.fee();
// Bound fee to [0, 50%]
fee = _bound(fee, 0, 50);
vm.prank(governor);
arm.setFee(fee * 100);
if (isConsoleAvailable) {
console.log(">>> ARM SetFees:\t Governor set ARM fee from %s% to %s%", oldFee / 100, fee);
}
sumUSDeFeesCollected += feesAccrued;
}
function targetARMRequestBaseWithdrawal(uint256 amount) external ensureExchangeRateIncrease {
uint256 balance = susde.balanceOf(address(arm));
if (assume(balance > 1)) return;
amount = _bound(amount, 1, Math.min(balance, type(uint88).max));
// Ensure there is an unstaker available
uint256 nextIndex = ethenaAssetAdapter.nextUnstakerIndex();
address unstaker = ethenaAssetAdapter.unstakers(nextIndex);
UserCooldown memory cooldown = susde.cooldowns(unstaker);
// If next unstaker has an active cooldown, this means all unstakers are in cooldown
// -> no unstaker available
if (assume(cooldown.underlyingAmount == 0)) return;
// Ensure time delay has passed
uint32 lastRequestTimestamp = ethenaAssetAdapter.lastRequestTimestamp();
uint256 requestDelay = ethenaAssetAdapter.DELAY_REQUEST();
if (block.timestamp < lastRequestTimestamp + requestDelay) {
if (isConsoleAvailable) {
console.log(
StdStyle.yellow(
string(
abi.encodePacked(
">>> Time jump:\t Fast forwarded to: ",
vm.toString(lastRequestTimestamp + requestDelay),
" (+ ",
vm.toString((lastRequestTimestamp + requestDelay) - block.timestamp),
"s)"
)
)
)
);
}
vm.warp(lastRequestTimestamp + requestDelay);
}
vm.prank(operator);
arm.requestBaseAssetRedeem(address(susde), amount);
unstakerIndices.push(nextIndex);
if (isConsoleAvailable) {
console.log(
">>> ARM ReqBaseW:\t Operator requested base withdrawal of %18e sUSDe underlying, using unstakers #%s",
amount,
nextIndex
);
}
sumSUSDeBaseRedeem += amount;
}
function targetARMClaimBaseWithdrawals(uint256) external ensureExchangeRateIncrease ensureTimeIncrease {
if (assume(unstakerIndices.length != 0)) return;
// Adapter claims are FIFO, so always claim the oldest pending unstaker.
uint256 selectedIndex = unstakerIndices[0];
address unstaker = ethenaAssetAdapter.unstakers(uint8(selectedIndex));
UserCooldown memory cooldown = susde.cooldowns(address(unstaker));
uint256 endTimestamp = cooldown.cooldownEnd;
// Fast forward time if needed
if (block.timestamp < endTimestamp) {
if (isConsoleAvailable) {
console.log(
StdStyle.yellow(
string(
abi.encodePacked(
">>> Time jump:\t Fast forwarded to: ",
vm.toString(endTimestamp),
" (+ ",
vm.toString(endTimestamp - block.timestamp),
"s)"
)
)
)
);
}
vm.warp(endTimestamp);
}
uint256 shares = ethenaAssetAdapter.requestShares(unstaker);
vm.prank(operator);
arm.claimBaseAssetRedeem(address(susde), shares);
// Remove the oldest unstaker index while preserving FIFO order.
for (uint256 i; i < unstakerIndices.length - 1; i++) {
unstakerIndices[i] = unstakerIndices[i + 1];
}
unstakerIndices.pop();
if (isConsoleAvailable) {
console.log(
string(
abi.encodePacked(
">>> ARM ClaimBaseW:\t Operator claimed base withdrawals using %s\t ", "who unstaked %18e USDe"
)
),
vm.getLabel(unstaker),
cooldown.underlyingAmount
);
}
sumUSDeBaseRedeem += cooldown.underlyingAmount;
}
// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║ ✦✦✦ SUSDE ✦✦✦ ║
// ╚══════════════════════════════════════════════════════════════════════════════╝
function targetSUSDeDeposit(uint256 amount) external ensureExchangeRateIncrease {
// Ensure we don't mint 0 shares.
uint256 totalAssets = susde.totalAssets();
uint256 totalSupply = susde.totalSupply();
uint256 minAmount = totalAssets / totalSupply + 1;
// Prevent zero deposits
amount = _bound(amount, minAmount, type(uint88).max);
// Mint amount to grace
MockERC20(address(usde)).mint(grace, amount);
// Deposit as grace
vm.prank(grace);
uint256 shares = susde.deposit(amount, grace);
if (isConsoleAvailable) {
console.log(
">>> sUSDe Deposit:\t Grace deposited %18e USDe\t and received %18e sUSDe shares", amount, shares
);
}
}
function targetSUSDeCooldownShares(uint256 shareAmount) external ensureExchangeRateIncrease {
// Cache balance
uint256 balance = susde.balanceOf(grace);
// Assume balance not zero
if (assume(balance > 1)) return;
// Bound shareAmount to [1, balance]
shareAmount = _bound(shareAmount, 1, balance);
// Cooldown shares as grace
vm.prank(grace);
uint256 amount = susde.cooldownShares(shareAmount);
if (isConsoleAvailable) {
console.log(
">>> sUSDe Cooldown:\t Grace cooled down %18e sUSDe shares\t for %18e USDe underlying",
shareAmount,
amount
);
}
}
function targetSUSDeUnstake() external ensureExchangeRateIncrease ensureTimeIncrease {
// Check grace's cooldown
UserCooldown memory cooldown = susde.cooldowns(grace);
// Ensure grace has a valid cooldown
if (assume(cooldown.cooldownEnd != 0)) return;
// Fast forward to after cooldown end if needed
if (block.timestamp < cooldown.cooldownEnd) {
if (isConsoleAvailable) {
console.log(
StdStyle.yellow(
string(
abi.encodePacked(
">>> Time jump:\t Fast forwarded to: ",
vm.toString(cooldown.cooldownEnd),
" (+ ",
vm.toString(cooldown.cooldownEnd - block.timestamp),
"s)"
)
)
)
);
}
vm.warp(cooldown.cooldownEnd);
}
// Unstake as grace
vm.prank(grace);
susde.unstake(grace);
if (isConsoleAvailable) {
console.log(
">>> sUSDe Unstake:\t Grace unstaked %18e USDe underlying after cooldown", cooldown.underlyingAmount
);
}
MockERC20(address(usde)).burn(grace, cooldown.underlyingAmount);
}
function targetSUSDeTransferInRewards(uint256 bps) external ensureExchangeRateIncrease ensureTimeIncrease {
// Ensure enough time has passed since last distribution
uint256 lastDistribution = susde.lastDistributionTimestamp();
if (block.timestamp < 8 hours + lastDistribution) {
// Fast forward time to allow rewards distribution
if (isConsoleAvailable) {
console.log(
StdStyle.yellow(
string(
abi.encodePacked(
">>> Time jump:\t Fast forwarded to: ",
vm.toString(lastDistribution + 8 hours),
" (+ ",
vm.toString((lastDistribution + 8 hours) - block.timestamp),
"s)"
)
)
)
);
}
vm.warp(lastDistribution + 8 hours);
}
uint256 balance = usde.balanceOf(address(susde));
// Rewards can be distributed 3/days max. 1bps at every distribution -> 10 APR.
bps = _bound(bps, 1, 10);
uint256 rewards = (balance * bps) / 10_000;
MockERC20(address(usde)).mint(governor, rewards);
vm.prank(governor);
susde.transferInRewards(rewards);
if (isConsoleAvailable) {
console.log(">>> sUSDe Rewards:\t Governor transferred in %18e USDe as rewards, bps: %d", rewards, bps);
}
}
// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║ ✦✦✦ MORPHO ✦✦✦ ║
// ╚══════════════════════════════════════════════════════════════════════════════╝
function targetMorphoDeposit(uint256 amount) external ensureExchangeRateIncrease {
// Ensure we don't mint 0 shares.
uint256 totalAssets = morpho.totalAssets();
uint256 totalSupply = morpho.totalSupply();
uint256 minAmount = totalAssets / totalSupply + 1;
// Prevent zero deposits
amount = _bound(amount, minAmount, type(uint88).max);
// Mint amount to harry
MockERC20(address(usde)).mint(harry, amount);
// Deposit as harry
vm.prank(harry);
uint256 shares = morpho.deposit(amount, harry);
if (isConsoleAvailable) {
console.log(
">>> Morpho Deposit:\t Harry deposited %18e USDe\t and received %18e Morpho shares", amount, shares
);
}
}
function targetMorphoWithdraw(uint256 amount) external ensureExchangeRateIncrease {
// Check harry's balance
uint256 balance = morpho.balanceOf(harry);
// Assume balance not zero
if (assume(balance > 1)) return;
// Bound shareAmount to [1, balance]
amount = _bound(amount, 1, balance);
// Ensure there is enough liquidity to withdraw the amount
uint256 maxWithdrawable = morpho.maxWithdraw(harry);
if (assume(amount <= maxWithdrawable)) return;
// Withdraw as harry
vm.prank(harry);
uint256 shares = morpho.withdraw(amount, harry, harry);
if (isConsoleAvailable) {
console.log(
">>> Morpho Withdraw:\t Harry withdrew %18e Morpho shares\t for %18e USDe underlying", shares, amount
);
}
MockERC20(address(usde)).burn(harry, amount);
}
function targetMorphoTransferInRewards(uint256 bps) external ensureExchangeRateIncrease {
uint256 balance = usde.balanceOf(address(morpho));
bps = _bound(bps, 1, 10);
uint256 rewards = (balance * bps) / 10_000;
MockERC20(address(usde)).mint(address(morpho), rewards);
if (isConsoleAvailable) {
console.log(">>> Morpho Rewards:\t Transferred in %18e USDe as rewards, bps: %d", rewards, bps);
}
}
function targetMorphoSetUtilizationRate(uint256 pct) external ensureExchangeRateIncrease {
pct = _bound(pct, 0, 100);
morpho.setUtilizationRate(pct * 1e16);
if (isConsoleAvailable) {
console.log(">>> Morpho UseRate:\t Governor set utilization rate to %s%", pct);
}
}
function _targetAfterAll() internal {
// In this function, we will simulate shutting down the ARM. This involves letting all users redeem their funds.
// This is important to ensure that the ARM can handle a complete withdrawal scenario without issues.
// This involves:
// 1. Claim all sUSDe base withdrawals
// 2. Request base withdrawal of the remaining sUSDe
// 3. Claim previous base withdrawals. At this point we shouldn't have any sUSDe left in the ARM.
// 4. Remove position from Morpho if any.
// 5. Let all ARM users (including dead address) redeem their shares.
// 6. Claim fees accrued.
// 1. Claim all sUSDe base withdrawals
// Fast forward time to allow claiming all previous base withdrawals
vm.warp(block.timestamp + 7 days);
for (uint256 i; i < unstakerIndices.length; i++) {
address unstaker = ethenaAssetAdapter.unstakers(uint8(unstakerIndices[i]));
uint256 shares = ethenaAssetAdapter.requestShares(unstaker);
vm.prank(operator);
arm.claimBaseAssetRedeem(address(susde), shares);
}
// 2. Request base withdrawal of the remaining sUSDe
uint256 susdeBalance = susde.balanceOf(address(arm));
uint256 nextIndex = ethenaAssetAdapter.nextUnstakerIndex();
if (susdeBalance > 0) {
vm.prank(operator);
arm.requestBaseAssetRedeem(address(susde), susdeBalance);
}
// 3. Claim previous base withdrawals. At this point we shouldn't have any sUSDe left in the ARM.
if (susdeBalance > 0) {
// Fast forward time to allow claiming the last base withdrawal
vm.warp(block.timestamp + 7 days);
address unstaker = ethenaAssetAdapter.unstakers(uint8(nextIndex));
uint256 shares = ethenaAssetAdapter.requestShares(unstaker);
vm.prank(operator);
arm.claimBaseAssetRedeem(address(susde), shares);
}
require(susde.balanceOf(address(arm)) == 0, "ARM still has sUSDe balance");
// 4. Remove position from Morpho if any.
address activeMarket = arm.activeMarket();
if (activeMarket != address(0)) {
morpho.setUtilizationRate(0);
vm.prank(operator);
arm.setActiveMarket(address(0));
}
// 5. Let all ARM users redeem their shares.
for (uint256 i; i < MAKERS_COUNT; i++) {
address user = makers[i];
uint256 balance = arm.balanceOf(user);
if (balance > 0) {
vm.prank(user);
arm.requestRedeem(balance);
}
}
// Fast forward time to allow claiming all redemptions
vm.warp(block.timestamp + DEFAULT_CLAIM_DELAY);
uint256 nextWithdrawalIndex = arm.nextWithdrawalIndex();
for (uint256 i; i < nextWithdrawalIndex; i++) {
(address user, bool claimed,,,) = arm.withdrawalRequests(i);
if (claimed) continue;
vm.prank(user);
arm.claimRedeem(i);
}
// 6. Claim fees accrued.
vm.prank(governor);
arm.collectFees();
}
}