-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathProtocolV3TestBase.sol
More file actions
1321 lines (1240 loc) · 50 KB
/
ProtocolV3TestBase.sol
File metadata and controls
1321 lines (1240 loc) · 50 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
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: AGPL-3.0
pragma solidity >=0.7.5 <0.9.0;
import 'forge-std/Test.sol';
import {IAaveOracle, IPool, IPoolAddressesProvider, IPoolDataProvider, IDefaultInterestRateStrategy, DataTypes, IPoolConfigurator} from 'aave-address-book/AaveV3.sol';
import {IERC20} from 'solidity-utils/contracts/oz-common/interfaces/IERC20.sol';
import {IERC20Metadata} from 'solidity-utils/contracts/oz-common/interfaces/IERC20Metadata.sol';
import {SafeERC20} from 'solidity-utils/contracts/oz-common/SafeERC20.sol';
import {ReserveConfiguration} from 'aave-v3-core/contracts/protocol/libraries/configuration/ReserveConfiguration.sol';
import {AaveV3EthereumAssets} from 'aave-address-book/AaveV3Ethereum.sol';
import {IInitializableAdminUpgradeabilityProxy} from './interfaces/IInitializableAdminUpgradeabilityProxy.sol';
import {ExtendedAggregatorV2V3Interface} from './interfaces/ExtendedAggregatorV2V3Interface.sol';
import {ProxyHelpers} from './ProxyHelpers.sol';
import {CommonTestBase, ReserveTokens} from './CommonTestBase.sol';
import {IDefaultInterestRateStrategyV2} from './dependencies/IDefaultInterestRateStrategyV2.sol';
struct ReserveConfig {
string symbol;
address underlying;
address aToken;
address stableDebtToken;
address variableDebtToken;
uint256 decimals;
uint256 ltv;
uint256 liquidationThreshold;
uint256 liquidationBonus;
uint256 liquidationProtocolFee;
uint256 reserveFactor;
bool usageAsCollateralEnabled;
bool borrowingEnabled;
address interestRateStrategy;
bool stableBorrowRateEnabled;
bool isPaused;
bool isActive;
bool isFrozen;
bool isSiloed;
bool isBorrowableInIsolation;
bool isFlashloanable;
uint256 supplyCap;
uint256 borrowCap;
uint256 debtCeiling;
uint256 eModeCategory;
}
struct LocalVars {
IPoolDataProvider.TokenData[] reserves;
ReserveConfig[] configs;
}
struct InterestStrategyValues {
address addressesProvider;
uint256 optimalUsageRatio;
uint256 optimalStableToTotalDebtRatio;
uint256 baseStableBorrowRate;
uint256 stableRateSlope1;
uint256 stableRateSlope2;
uint256 baseVariableBorrowRate;
uint256 variableRateSlope1;
uint256 variableRateSlope2;
}
/**
* only applicable to harmony at this point
*/
contract ProtocolV3TestBase is CommonTestBase {
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
using SafeERC20 for IERC20;
/**
* @dev runs the default test suite that should run on any proposal touching the aave protocol which includes:
* - diffing the config
* - checking if the changes are plausible (no conflicting config changes etc)
* - running an e2e testsuite over all assets
*/
function defaultTest(
string memory reportName,
IPool pool,
address payload
) public returns (ReserveConfig[] memory, ReserveConfig[] memory) {
return defaultTest(reportName, pool, payload, true);
}
function defaultTest(
string memory reportName,
IPool pool,
address payload,
bool runE2E
) public returns (ReserveConfig[] memory, ReserveConfig[] memory) {
string memory beforeString = string(abi.encodePacked(reportName, '_before'));
ReserveConfig[] memory configBefore = createConfigurationSnapshot(beforeString, pool);
executePayload(vm, payload);
string memory afterString = string(abi.encodePacked(reportName, '_after'));
ReserveConfig[] memory configAfter = createConfigurationSnapshot(afterString, pool);
diffReports(beforeString, afterString);
configChangePlausibilityTest(configBefore, configAfter);
if (runE2E) e2eTest(pool);
return (configBefore, configAfter);
}
function configChangePlausibilityTest(
ReserveConfig[] memory configBefore,
ReserveConfig[] memory configAfter
) public view {
uint256 configsBeforeLength = configBefore.length;
for (uint256 i = 0; i < configAfter.length; i++) {
// assets are usually not permanently unlisted, so the expectation is there will only be addition
// if config existed before
if (i < configsBeforeLength) {
// borrow increase should only happen on assets with borrowing enabled
// unless it is setting a borrow cap for the first time
if (
configBefore[i].borrowCap < configAfter[i].borrowCap && configBefore[i].borrowCap != 0
) {
require(configAfter[i].borrowingEnabled, 'PL_BORROW_CAP_BORROW_DISABLED');
}
} else {
// at least newly listed assets should never have a supply cap exceeding total supply
uint256 totalSupply = IERC20(configAfter[i].underlying).totalSupply();
require(
configAfter[i].supplyCap / 1e2 <=
totalSupply / IERC20Metadata(configAfter[i].underlying).decimals(),
'PL_SUPPLY_CAP_GT_TOTAL_SUPPLY'
);
}
// borrow cap should never exceed supply cap
if (
configAfter[i].borrowCap != 0 &&
configAfter[i].underlying != AaveV3EthereumAssets.GHO_UNDERLYING // GHO is the exclusion from the rule
) {
console.log(configAfter[i].underlying);
require(configAfter[i].borrowCap <= configAfter[i].supplyCap, 'PL_SUPPLY_LT_BORROW');
}
}
}
/**
* @dev Generates a markdown compatible snapshot of the whole pool configuration into `/reports`.
* @param reportName filename suffix for the generated reports.
* @param pool the pool to be snapshot
* @return ReserveConfig[] list of configs
*/
function createConfigurationSnapshot(
string memory reportName,
IPool pool
) public returns (ReserveConfig[] memory) {
return createConfigurationSnapshot(reportName, pool, true, true, true, true);
}
function createConfigurationSnapshot(
string memory reportName,
IPool pool,
bool reserveConfigs,
bool strategyConfigs,
bool eModeConigs,
bool poolConfigs
) public returns (ReserveConfig[] memory) {
string memory path = string(abi.encodePacked('./reports/', reportName, '.json'));
// overwrite with empty json to later be extended
vm.writeFile(
path,
'{ "eModes": {}, "reserves": {}, "strategies": {}, "poolConfiguration": {} }'
);
vm.serializeUint('root', 'chainId', block.chainid);
ReserveConfig[] memory configs = _getReservesConfigs(pool);
if (reserveConfigs) _writeReserveConfigs(path, configs, pool);
if (strategyConfigs) _writeStrategyConfigs(path, configs);
if (eModeConigs) _writeEModeConfigs(path, configs, pool);
if (poolConfigs) _writePoolConfiguration(path, pool);
return configs;
}
/**
* @dev Makes a e2e test including withdrawals/borrows and supplies to various reserves.
* @param pool the pool that should be tested
*/
function e2eTest(IPool pool) public {
ReserveConfig[] memory configs = _getReservesConfigs(pool);
ReserveConfig memory collateralConfig = _getGoodCollateral(configs);
uint256 snapshot = vm.snapshot();
for (uint256 i; i < configs.length; i++) {
if (_includeInE2e(configs[i])) {
e2eTestAsset(pool, collateralConfig, configs[i]);
vm.revertTo(snapshot);
} else {
console.log('E2E: TestAsset %s SKIPPED', configs[i].symbol);
}
}
}
function e2eTestAsset(
IPool pool,
ReserveConfig memory collateralConfig,
ReserveConfig memory testAssetConfig
) public {
console.log(
'E2E: Collateral %s, TestAsset %s',
collateralConfig.symbol,
testAssetConfig.symbol
);
address collateralSupplier = vm.addr(3);
address testAssetSupplier = vm.addr(4);
require(collateralConfig.usageAsCollateralEnabled, 'COLLATERAL_CONFIG_MUST_BE_COLLATERAL');
uint256 collateralAssetAmount = _getTokenAmountByDollarValue(pool, collateralConfig, 100000);
uint256 testAssetAmount = _getTokenAmountByDollarValue(pool, testAssetConfig, 1000);
// remove caps as they should not prevent testing
IPoolAddressesProvider addressesProvider = IPoolAddressesProvider(pool.ADDRESSES_PROVIDER());
IPoolConfigurator poolConfigurator = IPoolConfigurator(addressesProvider.getPoolConfigurator());
vm.startPrank(addressesProvider.getACLAdmin());
if (collateralConfig.supplyCap != 0)
poolConfigurator.setSupplyCap(collateralConfig.underlying, 0);
if (testAssetConfig.supplyCap != 0)
poolConfigurator.setSupplyCap(testAssetConfig.underlying, 0);
if (testAssetConfig.borrowCap != 0)
poolConfigurator.setBorrowCap(testAssetConfig.underlying, 0);
vm.stopPrank();
// GHO is a special case as it cannot be supplied
if (testAssetConfig.underlying == AaveV3EthereumAssets.GHO_UNDERLYING) {
_deposit(collateralConfig, pool, collateralSupplier, collateralAssetAmount);
uint256 snapshot = vm.snapshot();
// test variable borrowing
if (testAssetConfig.borrowingEnabled) {
_e2eTestBorrowRepay(pool, collateralSupplier, testAssetConfig, testAssetAmount, false);
vm.revertTo(snapshot);
// test stable borrowing
if (testAssetConfig.stableBorrowRateEnabled) {
_e2eTestBorrowRepay(pool, collateralSupplier, testAssetConfig, testAssetAmount, true);
vm.revertTo(snapshot);
}
}
} else {
_deposit(collateralConfig, pool, collateralSupplier, collateralAssetAmount);
_deposit(testAssetConfig, pool, testAssetSupplier, testAssetAmount);
uint256 snapshot = vm.snapshot();
// test withdrawal
_withdraw(testAssetConfig, pool, testAssetSupplier, testAssetAmount / 2);
_withdraw(testAssetConfig, pool, testAssetSupplier, type(uint256).max);
vm.revertTo(snapshot);
// test variable borrowing
if (testAssetConfig.borrowingEnabled) {
if (
(testAssetConfig.borrowCap * 10 ** testAssetConfig.decimals) <
IERC20(testAssetConfig.variableDebtToken).totalSupply() + testAssetAmount
) {
console.log('Skip Borrowing: %s, borrow cap fully utilized', testAssetConfig.symbol);
return;
}
_e2eTestBorrowRepay(pool, collateralSupplier, testAssetConfig, testAssetAmount, false);
vm.revertTo(snapshot);
// test stable borrowing
if (testAssetConfig.stableBorrowRateEnabled) {
_e2eTestBorrowRepay(pool, collateralSupplier, testAssetConfig, testAssetAmount, true);
vm.revertTo(snapshot);
}
}
}
}
/**
* Reserves that are frozen or not active should not be included in e2e test suite
*/
function _includeInE2e(ReserveConfig memory config) internal pure returns (bool) {
return !config.isFrozen && config.isActive && !config.isPaused;
}
function _getTokenAmountByDollarValue(
IPool pool,
ReserveConfig memory config,
uint256 dollarValue
) internal view returns (uint256) {
IPoolAddressesProvider addressesProvider = IPoolAddressesProvider(pool.ADDRESSES_PROVIDER());
IAaveOracle oracle = IAaveOracle(addressesProvider.getPriceOracle());
uint256 latestAnswer = oracle.getAssetPrice(config.underlying);
return (dollarValue * 10 ** (8 + config.decimals)) / latestAnswer;
}
function _e2eTestBorrowRepay(
IPool pool,
address borrower,
ReserveConfig memory testAssetConfig,
uint256 amount,
bool stable
) internal {
this._borrow(testAssetConfig, pool, borrower, amount, stable);
// switching back and forth between rate modes should work
if (testAssetConfig.stableBorrowRateEnabled) {
vm.startPrank(borrower);
pool.swapBorrowRateMode(testAssetConfig.underlying, stable ? 1 : 2);
pool.swapBorrowRateMode(testAssetConfig.underlying, stable ? 2 : 1);
} else {
vm.expectRevert();
pool.swapBorrowRateMode(testAssetConfig.underlying, stable ? 1 : 2);
}
_repay(testAssetConfig, pool, borrower, amount, stable);
}
/**
* @dev returns a "good" collateral in the list that cannot be borrowed in stable mode
*/
function _getGoodCollateral(
ReserveConfig[] memory configs
) private pure returns (ReserveConfig memory config) {
for (uint256 i = 0; i < configs.length; i++) {
if (
// not frozen etc
_includeInE2e(configs[i]) &&
// usable as collateral
configs[i].usageAsCollateralEnabled &&
// not stable borrowable as this makes testing stable borrowing unnecessary hard to reason about
!configs[i].stableBorrowRateEnabled &&
// not isolated asset as we can only borrow stablecoins against it
configs[i].debtCeiling == 0
) return configs[i];
}
revert('ERROR: No usable collateral found');
}
function _deposit(
ReserveConfig memory config,
IPool pool,
address user,
uint256 amount
) internal {
require(!config.isFrozen, 'DEPOSIT(): FROZEN_RESERVE');
require(config.isActive, 'DEPOSIT(): INACTIVE_RESERVE');
require(!config.isPaused, 'DEPOSIT(): PAUSED_RESERVE');
vm.startPrank(user);
uint256 aTokenBefore = IERC20(config.aToken).balanceOf(user);
deal2(config.underlying, user, amount);
IERC20(config.underlying).forceApprove(address(pool), amount);
console.log('SUPPLY: %s, Amount: %s', config.symbol, amount);
pool.deposit(config.underlying, amount, user, 0);
uint256 aTokenAfter = IERC20(config.aToken).balanceOf(user);
assertApproxEqAbs(aTokenAfter, aTokenBefore + amount, 1);
vm.stopPrank();
}
function _withdraw(
ReserveConfig memory config,
IPool pool,
address user,
uint256 amount
) internal returns (uint256) {
vm.startPrank(user);
uint256 aTokenBefore = IERC20(config.aToken).balanceOf(user);
uint256 amountOut = pool.withdraw(config.underlying, amount, user);
console.log('WITHDRAW: %s, Amount: %s', config.symbol, amountOut);
uint256 aTokenAfter = IERC20(config.aToken).balanceOf(user);
if (aTokenBefore < amount) {
require(aTokenAfter == 0, '_withdraw(): DUST_AFTER_WITHDRAW_ALL');
} else {
assertApproxEqAbs(aTokenAfter, aTokenBefore - amount, 1);
}
vm.stopPrank();
return amountOut;
}
function _borrow(
ReserveConfig memory config,
IPool pool,
address user,
uint256 amount,
bool stable
) external {
vm.startPrank(user);
address debtToken = stable ? config.stableDebtToken : config.variableDebtToken;
uint256 debtBefore = IERC20(debtToken).balanceOf(user);
console.log('BORROW: %s, Amount %s, Stable: %s', config.symbol, amount, stable);
pool.borrow(config.underlying, amount, stable ? 1 : 2, 0, user);
uint256 debtAfter = IERC20(debtToken).balanceOf(user);
assertApproxEqAbs(debtAfter, debtBefore + amount, 1);
vm.stopPrank();
}
function _repay(
ReserveConfig memory config,
IPool pool,
address user,
uint256 amount,
bool stable
) internal {
vm.startPrank(user);
address debtToken = stable ? config.stableDebtToken : config.variableDebtToken;
uint256 debtBefore = IERC20(debtToken).balanceOf(user);
deal2(config.underlying, user, amount);
IERC20(config.underlying).forceApprove(address(pool), amount);
console.log('REPAY: %s, Amount: %s', config.symbol, amount);
pool.repay(config.underlying, amount, stable ? 1 : 2, user);
uint256 debtAfter = IERC20(debtToken).balanceOf(user);
if (amount >= debtBefore) {
assertEq(debtAfter, 0, '_repay() : ERROR MUST_BE_ZERO');
} else {
assertApproxEqAbs(debtAfter, debtBefore - amount, 1, '_repay() : ERROR MAX_ONE_OFF');
}
vm.stopPrank();
}
function _writeEModeConfigs(
string memory path,
ReserveConfig[] memory configs,
IPool pool
) internal {
// keys for json stringification
string memory eModesKey = 'emodes';
string memory content = '{}';
vm.serializeJson(eModesKey, '{}');
uint256[] memory usedCategories = new uint256[](configs.length);
for (uint256 i = 0; i < configs.length; i++) {
if (!_isInUint256Array(usedCategories, configs[i].eModeCategory)) {
usedCategories[i] = configs[i].eModeCategory;
DataTypes.EModeCategory memory category = pool.getEModeCategoryData(
uint8(configs[i].eModeCategory)
);
string memory key = vm.toString(configs[i].eModeCategory);
vm.serializeJson(key, '{}');
vm.serializeUint(key, 'eModeCategory', configs[i].eModeCategory);
vm.serializeString(key, 'label', category.label);
vm.serializeUint(key, 'ltv', category.ltv);
vm.serializeUint(key, 'liquidationThreshold', category.liquidationThreshold);
vm.serializeUint(key, 'liquidationBonus', category.liquidationBonus);
string memory object = vm.serializeAddress(key, 'priceSource', category.priceSource);
content = vm.serializeString(eModesKey, key, object);
}
}
string memory output = vm.serializeString('root', 'eModes', content);
vm.writeJson(output, path);
}
function _writeStrategyConfigs(string memory path, ReserveConfig[] memory configs) internal {
// keys for json stringification
string memory strategiesKey = 'stategies';
string memory content = '{}';
vm.serializeJson(strategiesKey, '{}');
for (uint256 i = 0; i < configs.length; i++) {
IDefaultInterestRateStrategyV2 strategyV2 = IDefaultInterestRateStrategyV2(
configs[i].interestRateStrategy
);
IDefaultInterestRateStrategy strategyV1 = IDefaultInterestRateStrategy(
configs[i].interestRateStrategy
);
address asset = configs[i].underlying;
string memory key = vm.toString(asset);
vm.serializeJson(key, '{}');
vm.serializeString(key, 'address', vm.toString(configs[i].interestRateStrategy));
string memory object;
try strategyV1.getVariableRateSlope1() {
vm.serializeString(
key,
'baseStableBorrowRate',
vm.toString(strategyV1.getBaseStableBorrowRate())
);
vm.serializeString(key, 'stableRateSlope1', vm.toString(strategyV1.getStableRateSlope1()));
vm.serializeString(key, 'stableRateSlope2', vm.toString(strategyV1.getStableRateSlope2()));
vm.serializeString(
key,
'baseVariableBorrowRate',
vm.toString(strategyV1.getBaseVariableBorrowRate())
);
vm.serializeString(
key,
'variableRateSlope1',
vm.toString(strategyV1.getVariableRateSlope1())
);
vm.serializeString(
key,
'variableRateSlope2',
vm.toString(strategyV1.getVariableRateSlope2())
);
vm.serializeString(
key,
'optimalStableToTotalDebtRatio',
vm.toString(strategyV1.OPTIMAL_STABLE_TO_TOTAL_DEBT_RATIO())
);
vm.serializeString(
key,
'maxExcessStableToTotalDebtRatio',
vm.toString(strategyV1.MAX_EXCESS_STABLE_TO_TOTAL_DEBT_RATIO())
);
vm.serializeString(key, 'optimalUsageRatio', vm.toString(strategyV1.OPTIMAL_USAGE_RATIO()));
object = vm.serializeString(
key,
'maxExcessUsageRatio',
vm.toString(strategyV1.MAX_EXCESS_USAGE_RATIO())
);
} catch {
vm.serializeString(
key,
'baseVariableBorrowRate',
vm.toString(strategyV2.getBaseVariableBorrowRate(asset))
);
vm.serializeString(
key,
'variableRateSlope1',
vm.toString(strategyV2.getVariableRateSlope1(asset))
);
vm.serializeString(
key,
'variableRateSlope2',
vm.toString(strategyV2.getVariableRateSlope2(asset))
);
vm.serializeString(
key,
'maxVariableBorrowRate',
vm.toString(strategyV2.getMaxVariableBorrowRate(asset))
);
object = vm.serializeString(
key,
'optimalUsageRatio',
vm.toString(strategyV2.getOptimalUsageRatio(asset))
);
}
content = vm.serializeString(strategiesKey, key, object);
}
string memory output = vm.serializeString('root', 'strategies', content);
vm.writeJson(output, path);
}
function _writeReserveConfigs(
string memory path,
ReserveConfig[] memory configs,
IPool pool
) internal {
// keys for json stringification
string memory reservesKey = 'reserves';
string memory content = '{}';
vm.serializeJson(reservesKey, '{}');
IPoolAddressesProvider addressesProvider = IPoolAddressesProvider(pool.ADDRESSES_PROVIDER());
IAaveOracle oracle = IAaveOracle(addressesProvider.getPriceOracle());
for (uint256 i = 0; i < configs.length; i++) {
ReserveConfig memory config = configs[i];
ExtendedAggregatorV2V3Interface assetOracle = ExtendedAggregatorV2V3Interface(
oracle.getSourceOfAsset(config.underlying)
);
DataTypes.ReserveData memory reserveData = pool.getReserveData(config.underlying);
string memory key = vm.toString(config.underlying);
vm.serializeJson(key, '{}');
vm.serializeString(key, 'symbol', config.symbol);
vm.serializeUint(key, 'ltv', config.ltv);
vm.serializeUint(key, 'liquidationThreshold', config.liquidationThreshold);
vm.serializeUint(key, 'liquidationBonus', config.liquidationBonus);
vm.serializeUint(key, 'liquidationProtocolFee', config.liquidationProtocolFee);
vm.serializeUint(key, 'reserveFactor', config.reserveFactor);
vm.serializeUint(key, 'decimals', config.decimals);
vm.serializeUint(key, 'borrowCap', config.borrowCap);
vm.serializeUint(key, 'supplyCap', config.supplyCap);
vm.serializeUint(key, 'debtCeiling', config.debtCeiling);
vm.serializeUint(key, 'eModeCategory', config.eModeCategory);
vm.serializeUint(key, 'liquidityIndex', reserveData.liquidityIndex);
vm.serializeUint(key, 'currentLiquidityRate', reserveData.currentLiquidityRate);
vm.serializeUint(key, 'variableBorrowIndex', reserveData.variableBorrowIndex);
vm.serializeUint(key, 'currentVariableBorrowRate', reserveData.currentVariableBorrowRate);
vm.serializeBool(key, 'usageAsCollateralEnabled', config.usageAsCollateralEnabled);
vm.serializeBool(key, 'borrowingEnabled', config.borrowingEnabled);
vm.serializeBool(key, 'stableBorrowRateEnabled', config.stableBorrowRateEnabled);
vm.serializeBool(key, 'isPaused', config.isPaused);
vm.serializeBool(key, 'isActive', config.isActive);
vm.serializeBool(key, 'isFrozen', config.isFrozen);
vm.serializeBool(key, 'isSiloed', config.isSiloed);
vm.serializeBool(key, 'isBorrowableInIsolation', config.isBorrowableInIsolation);
vm.serializeBool(key, 'isFlashloanable', config.isFlashloanable);
vm.serializeAddress(key, 'interestRateStrategy', config.interestRateStrategy);
vm.serializeAddress(key, 'underlying', config.underlying);
vm.serializeAddress(key, 'aToken', config.aToken);
vm.serializeAddress(key, 'stableDebtToken', config.stableDebtToken);
vm.serializeAddress(key, 'variableDebtToken', config.variableDebtToken);
vm.serializeAddress(
key,
'aTokenImpl',
ProxyHelpers.getInitializableAdminUpgradeabilityProxyImplementation(vm, config.aToken)
);
vm.serializeString(key, 'aTokenSymbol', IERC20Metadata(config.aToken).symbol());
vm.serializeString(key, 'aTokenName', IERC20Metadata(config.aToken).name());
vm.serializeAddress(
key,
'stableDebtTokenImpl',
ProxyHelpers.getInitializableAdminUpgradeabilityProxyImplementation(
vm,
config.stableDebtToken
)
);
vm.serializeString(
key,
'stableDebtTokenSymbol',
IERC20Metadata(config.stableDebtToken).symbol()
);
vm.serializeString(key, 'stableDebtTokenName', IERC20Metadata(config.stableDebtToken).name());
vm.serializeAddress(
key,
'variableDebtTokenImpl',
ProxyHelpers.getInitializableAdminUpgradeabilityProxyImplementation(
vm,
config.variableDebtToken
)
);
vm.serializeString(
key,
'variableDebtTokenSymbol',
IERC20Metadata(config.variableDebtToken).symbol()
);
vm.serializeString(
key,
'variableDebtTokenName',
IERC20Metadata(config.variableDebtToken).name()
);
vm.serializeAddress(key, 'oracle', address(assetOracle));
if (address(assetOracle) != address(0)) {
try assetOracle.description() returns (string memory name) {
vm.serializeString(key, 'oracleDescription', name);
} catch {
try assetOracle.name() returns (string memory name) {
vm.serializeString(key, 'oracleName', name);
} catch {}
}
try assetOracle.decimals() returns (uint8 decimals) {
vm.serializeUint(key, 'oracleDecimals', decimals);
} catch {
try assetOracle.DECIMALS() returns (uint8 decimals) {
vm.serializeUint(key, 'oracleDecimals', decimals);
} catch {}
}
}
string memory out = vm.serializeUint(
key,
'oracleLatestAnswer',
uint256(oracle.getAssetPrice(config.underlying))
);
content = vm.serializeString(reservesKey, key, out);
}
string memory output = vm.serializeString('root', 'reserves', content);
vm.writeJson(output, path);
}
function _writePoolConfiguration(string memory path, IPool pool) internal {
// keys for json stringification
string memory poolConfigKey = 'poolConfig';
// addresses provider
IPoolAddressesProvider addressesProvider = IPoolAddressesProvider(pool.ADDRESSES_PROVIDER());
vm.serializeAddress(poolConfigKey, 'poolAddressesProvider', address(addressesProvider));
// oracles
vm.serializeAddress(poolConfigKey, 'oracle', addressesProvider.getPriceOracle());
vm.serializeAddress(
poolConfigKey,
'priceOracleSentinel',
addressesProvider.getPriceOracleSentinel()
);
// pool configurator
IPoolConfigurator configurator = IPoolConfigurator(addressesProvider.getPoolConfigurator());
vm.serializeAddress(poolConfigKey, 'poolConfigurator', address(configurator));
vm.serializeAddress(
poolConfigKey,
'poolConfiguratorImpl',
ProxyHelpers.getInitializableAdminUpgradeabilityProxyImplementation(vm, address(configurator))
);
// PoolDataProvider
IPoolDataProvider pdp = IPoolDataProvider(addressesProvider.getPoolDataProvider());
vm.serializeAddress(poolConfigKey, 'protocolDataProvider', address(pdp));
// pool
vm.serializeAddress(
poolConfigKey,
'poolImpl',
ProxyHelpers.getInitializableAdminUpgradeabilityProxyImplementation(vm, address(pool))
);
string memory content = vm.serializeAddress(poolConfigKey, 'pool', address(pool));
string memory output = vm.serializeString('root', 'poolConfig', content);
vm.writeJson(output, path);
}
function _getReservesConfigs(IPool pool) internal view returns (ReserveConfig[] memory) {
IPoolAddressesProvider addressesProvider = IPoolAddressesProvider(pool.ADDRESSES_PROVIDER());
IPoolDataProvider poolDataProvider = IPoolDataProvider(addressesProvider.getPoolDataProvider());
LocalVars memory vars;
vars.reserves = poolDataProvider.getAllReservesTokens();
vars.configs = new ReserveConfig[](vars.reserves.length);
for (uint256 i = 0; i < vars.reserves.length; i++) {
vars.configs[i] = _getStructReserveConfig(pool, vars.reserves[i]);
ReserveTokens memory reserveTokens = _getStructReserveTokens(
poolDataProvider,
vars.configs[i].underlying
);
vars.configs[i].aToken = reserveTokens.aToken;
vars.configs[i].variableDebtToken = reserveTokens.variableDebtToken;
vars.configs[i].stableDebtToken = reserveTokens.stableDebtToken;
}
return vars.configs;
}
function _getStructReserveTokens(
IPoolDataProvider pdp,
address underlyingAddress
) internal view returns (ReserveTokens memory) {
ReserveTokens memory reserveTokens;
(reserveTokens.aToken, reserveTokens.stableDebtToken, reserveTokens.variableDebtToken) = pdp
.getReserveTokensAddresses(underlyingAddress);
return reserveTokens;
}
function _getStructReserveConfig(
IPool pool,
IPoolDataProvider.TokenData memory reserve
) internal view virtual returns (ReserveConfig memory) {
ReserveConfig memory localConfig;
DataTypes.ReserveConfigurationMap memory configuration = pool.getConfiguration(
reserve.tokenAddress
);
localConfig.interestRateStrategy = pool
.getReserveData(reserve.tokenAddress)
.interestRateStrategyAddress;
(
localConfig.ltv,
localConfig.liquidationThreshold,
localConfig.liquidationBonus,
localConfig.decimals,
localConfig.reserveFactor,
localConfig.eModeCategory
) = configuration.getParams();
(
localConfig.isActive,
localConfig.isFrozen,
localConfig.borrowingEnabled,
localConfig.stableBorrowRateEnabled,
localConfig.isPaused
) = configuration.getFlags();
localConfig.symbol = reserve.symbol;
localConfig.underlying = reserve.tokenAddress;
localConfig.usageAsCollateralEnabled = localConfig.liquidationThreshold != 0;
localConfig.isSiloed = configuration.getSiloedBorrowing();
(localConfig.borrowCap, localConfig.supplyCap) = configuration.getCaps();
localConfig.debtCeiling = configuration.getDebtCeiling();
localConfig.liquidationProtocolFee = configuration.getLiquidationProtocolFee();
localConfig.isBorrowableInIsolation = configuration.getBorrowableInIsolation();
localConfig.isFlashloanable = configuration.getFlashLoanEnabled();
return localConfig;
}
// TODO This should probably be simplified with assembly, too much boilerplate
function _clone(ReserveConfig memory config) internal pure returns (ReserveConfig memory) {
return
ReserveConfig({
symbol: config.symbol,
underlying: config.underlying,
aToken: config.aToken,
stableDebtToken: config.stableDebtToken,
variableDebtToken: config.variableDebtToken,
decimals: config.decimals,
ltv: config.ltv,
liquidationThreshold: config.liquidationThreshold,
liquidationBonus: config.liquidationBonus,
liquidationProtocolFee: config.liquidationProtocolFee,
reserveFactor: config.reserveFactor,
usageAsCollateralEnabled: config.usageAsCollateralEnabled,
borrowingEnabled: config.borrowingEnabled,
interestRateStrategy: config.interestRateStrategy,
stableBorrowRateEnabled: config.stableBorrowRateEnabled,
isPaused: config.isPaused,
isActive: config.isActive,
isFrozen: config.isFrozen,
isSiloed: config.isSiloed,
isBorrowableInIsolation: config.isBorrowableInIsolation,
isFlashloanable: config.isFlashloanable,
supplyCap: config.supplyCap,
borrowCap: config.borrowCap,
debtCeiling: config.debtCeiling,
eModeCategory: config.eModeCategory
});
}
function _findReserveConfig(
ReserveConfig[] memory configs,
address underlying
) internal pure returns (ReserveConfig memory) {
for (uint256 i = 0; i < configs.length; i++) {
if (configs[i].underlying == underlying) {
// Important to clone the struct, to avoid unexpected side effect if modifying the returned config
return _clone(configs[i]);
}
}
revert('RESERVE_CONFIG_NOT_FOUND');
}
function _findReserveConfigBySymbol(
ReserveConfig[] memory configs,
string memory symbolOfUnderlying
) internal pure returns (ReserveConfig memory) {
for (uint256 i = 0; i < configs.length; i++) {
if (
keccak256(abi.encodePacked(configs[i].symbol)) ==
keccak256(abi.encodePacked(symbolOfUnderlying))
) {
return _clone(configs[i]);
}
}
revert('RESERVE_CONFIG_NOT_FOUND');
}
function _logReserveConfig(ReserveConfig memory config) internal view {
console.log('Symbol ', config.symbol);
console.log('Underlying address ', config.underlying);
console.log('AToken address ', config.aToken);
console.log('Stable debt token address ', config.stableDebtToken);
console.log('Variable debt token address ', config.variableDebtToken);
console.log('Decimals ', config.decimals);
console.log('LTV ', config.ltv);
console.log('Liquidation Threshold ', config.liquidationThreshold);
console.log('Liquidation Bonus ', config.liquidationBonus);
console.log('Liquidation protocol fee ', config.liquidationProtocolFee);
console.log('Reserve Factor ', config.reserveFactor);
console.log('Usage as collateral enabled ', (config.usageAsCollateralEnabled) ? 'Yes' : 'No');
console.log('Borrowing enabled ', (config.borrowingEnabled) ? 'Yes' : 'No');
console.log('Stable borrow rate enabled ', (config.stableBorrowRateEnabled) ? 'Yes' : 'No');
console.log('Supply cap ', config.supplyCap);
console.log('Borrow cap ', config.borrowCap);
console.log('Debt ceiling ', config.debtCeiling);
console.log('eMode category ', config.eModeCategory);
console.log('Interest rate strategy ', config.interestRateStrategy);
console.log('Is active ', (config.isActive) ? 'Yes' : 'No');
console.log('Is frozen ', (config.isFrozen) ? 'Yes' : 'No');
console.log('Is siloed ', (config.isSiloed) ? 'Yes' : 'No');
console.log('Is borrowable in isolation ', (config.isBorrowableInIsolation) ? 'Yes' : 'No');
console.log('Is flashloanable ', (config.isFlashloanable) ? 'Yes' : 'No');
console.log('-----');
console.log('-----');
}
function _validateReserveConfig(
ReserveConfig memory expectedConfig,
ReserveConfig[] memory allConfigs
) internal pure {
ReserveConfig memory config = _findReserveConfig(allConfigs, expectedConfig.underlying);
require(
keccak256(bytes(config.symbol)) == keccak256(bytes(expectedConfig.symbol)),
'_validateReserveConfig() : INVALID_SYMBOL'
);
require(
config.underlying == expectedConfig.underlying,
'_validateReserveConfig() : INVALID_UNDERLYING'
);
require(config.decimals == expectedConfig.decimals, '_validateReserveConfig: INVALID_DECIMALS');
require(config.ltv == expectedConfig.ltv, '_validateReserveConfig: INVALID_LTV');
require(
config.liquidationThreshold == expectedConfig.liquidationThreshold,
'_validateReserveConfig: INVALID_LIQ_THRESHOLD'
);
require(
config.liquidationBonus == expectedConfig.liquidationBonus,
'_validateReserveConfig: INVALID_LIQ_BONUS'
);
require(
config.liquidationProtocolFee == expectedConfig.liquidationProtocolFee,
'_validateReserveConfig: INVALID_LIQUIDATION_PROTOCOL_FEE'
);
require(
config.reserveFactor == expectedConfig.reserveFactor,
'_validateReserveConfig: INVALID_RESERVE_FACTOR'
);
require(
config.usageAsCollateralEnabled == expectedConfig.usageAsCollateralEnabled,
'_validateReserveConfig: INVALID_USAGE_AS_COLLATERAL'
);
require(
config.borrowingEnabled == expectedConfig.borrowingEnabled,
'_validateReserveConfig: INVALID_BORROWING_ENABLED'
);
require(
config.stableBorrowRateEnabled == expectedConfig.stableBorrowRateEnabled,
'_validateReserveConfig: INVALID_STABLE_BORROW_ENABLED'
);
require(
config.isActive == expectedConfig.isActive,
'_validateReserveConfig: INVALID_IS_ACTIVE'
);
require(
config.isFrozen == expectedConfig.isFrozen,
'_validateReserveConfig: INVALID_IS_FROZEN'
);
require(
config.isSiloed == expectedConfig.isSiloed,
'_validateReserveConfig: INVALID_IS_SILOED'
);
require(
config.isBorrowableInIsolation == expectedConfig.isBorrowableInIsolation,
'_validateReserveConfig: INVALID_IS_BORROWABLE_IN_ISOLATION'
);
require(
config.isFlashloanable == expectedConfig.isFlashloanable,
'_validateReserveConfig: INVALID_IS_FLASHLOANABLE'
);
require(
config.supplyCap == expectedConfig.supplyCap,
'_validateReserveConfig: INVALID_SUPPLY_CAP'
);
require(
config.borrowCap == expectedConfig.borrowCap,
'_validateReserveConfig: INVALID_BORROW_CAP'
);
require(
config.debtCeiling == expectedConfig.debtCeiling,
'_validateReserveConfig: INVALID_DEBT_CEILING'
);
require(
config.eModeCategory == expectedConfig.eModeCategory,
'_validateReserveConfig: INVALID_EMODE_CATEGORY'
);
require(
config.interestRateStrategy == expectedConfig.interestRateStrategy,
'_validateReserveConfig: INVALID_INTEREST_RATE_STRATEGY'
);
}
// TODO: deprecated, remove it later
function _validateInterestRateStrategy(
address interestRateStrategyAddress,
address expectedStrategy,
InterestStrategyValues memory expectedStrategyValues
) internal view {
IDefaultInterestRateStrategy strategy = IDefaultInterestRateStrategy(
interestRateStrategyAddress
);
require(
address(strategy) == expectedStrategy,
'_validateInterestRateStrategy() : INVALID_STRATEGY_ADDRESS'
);
require(
strategy.OPTIMAL_USAGE_RATIO() == expectedStrategyValues.optimalUsageRatio,
'_validateInterestRateStrategy() : INVALID_OPTIMAL_RATIO'
);
require(
strategy.OPTIMAL_STABLE_TO_TOTAL_DEBT_RATIO() ==
expectedStrategyValues.optimalStableToTotalDebtRatio,
'_validateInterestRateStrategy() : INVALID_OPTIMAL_STABLE_TO_TOTAL_DEBT_RATIO'
);
require(
address(strategy.ADDRESSES_PROVIDER()) == expectedStrategyValues.addressesProvider,
'_validateInterestRateStrategy() : INVALID_ADDRESSES_PROVIDER'
);
require(
strategy.getBaseVariableBorrowRate() == expectedStrategyValues.baseVariableBorrowRate,
'_validateInterestRateStrategy() : INVALID_BASE_VARIABLE_BORROW'
);
require(
strategy.getBaseStableBorrowRate() == expectedStrategyValues.baseStableBorrowRate,
'_validateInterestRateStrategy() : INVALID_BASE_STABLE_BORROW'
);
require(
strategy.getStableRateSlope1() == expectedStrategyValues.stableRateSlope1,
'_validateInterestRateStrategy() : INVALID_STABLE_SLOPE_1'
);
require(
strategy.getStableRateSlope2() == expectedStrategyValues.stableRateSlope2,
'_validateInterestRateStrategy() : INVALID_STABLE_SLOPE_2'
);
require(
strategy.getVariableRateSlope1() == expectedStrategyValues.variableRateSlope1,
'_validateInterestRateStrategy() : INVALID_VARIABLE_SLOPE_1'
);
require(
strategy.getVariableRateSlope2() == expectedStrategyValues.variableRateSlope2,
'_validateInterestRateStrategy() : INVALID_VARIABLE_SLOPE_2'
);
}
function _validateInterestRateStrategy(
address reserve,
address interestRateStrategyAddress,
address expectedStrategy,
IDefaultInterestRateStrategyV2.InterestRateDataRay memory expectedStrategyValues
) internal view {
IDefaultInterestRateStrategyV2 strategy = IDefaultInterestRateStrategyV2(
interestRateStrategyAddress
);
require(
address(strategy) == expectedStrategy,
'_validateInterestRateStrategy() : INVALID_STRATEGY_ADDRESS'