generated from jbx-protocol/juice-contract-template
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathREVLoansSourced.t.sol
1588 lines (1263 loc) · 66.9 KB
/
REVLoansSourced.t.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: MIT
pragma solidity 0.8.23;
import "forge-std/Test.sol";
import /* {*} from */ "@bananapus/core/test/helpers/TestBaseWorkflow.sol";
import /* {*} from "@bananapus/721-hook/src/JB721TiersHookDeployer.sol";
import /* {*} from */ "./../src/REVDeployer.sol";
import "@croptop/core/src/CTPublisher.sol";
import "@bananapus/core/script/helpers/CoreDeploymentLib.sol";
import "@bananapus/721-hook/script/helpers/Hook721DeploymentLib.sol";
import "@bananapus/suckers/script/helpers/SuckerDeploymentLib.sol";
import "@croptop/core/script/helpers/CroptopDeploymentLib.sol";
import "@bananapus/swap-terminal/script/helpers/SwapTerminalDeploymentLib.sol";
import "@bananapus/buyback-hook/script/helpers/BuybackDeploymentLib.sol";
import {JBConstants} from "@bananapus/core/src/libraries/JBConstants.sol";
import {JBAccountingContext} from "@bananapus/core/src/structs/JBAccountingContext.sol";
import {MockPriceFeed} from "@bananapus/core/test/mock/MockPriceFeed.sol";
import {MockERC20} from "@bananapus/core/test/mock/MockERC20.sol";
import {REVLoans} from "../src/REVLoans.sol";
import {REVLoan} from "../src/structs/REVLoan.sol";
import {REVStageConfig, REVAutoIssuance} from "../src/structs/REVStageConfig.sol";
import {REVLoanSource} from "../src/structs/REVLoanSource.sol";
import {REVDescription} from "../src/structs/REVDescription.sol";
import {REVBuybackPoolConfig} from "../src/structs/REVBuybackPoolConfig.sol";
import {IREVLoans} from "./../src/interfaces/IREVLoans.sol";
import {JBSuckerDeployerConfig} from "@bananapus/suckers/src/structs/JBSuckerDeployerConfig.sol";
import {JBSuckerRegistry} from "@bananapus/suckers/src/JBSuckerRegistry.sol";
import {JB721TiersHookDeployer} from "@bananapus/721-hook/src/JB721TiersHookDeployer.sol";
import {JB721TiersHook} from "@bananapus/721-hook/src/JB721TiersHook.sol";
import {JB721TiersHookStore} from "@bananapus/721-hook/src/JB721TiersHookStore.sol";
import {JBAddressRegistry} from "@bananapus/address-registry/src/JBAddressRegistry.sol";
import {IJBAddressRegistry} from "@bananapus/address-registry/src/interfaces/IJBAddressRegistry.sol";
struct FeeProjectConfig {
REVConfig configuration;
JBTerminalConfig[] terminalConfigurations;
REVBuybackHookConfig buybackHookConfiguration;
REVSuckerDeploymentConfig suckerDeploymentConfiguration;
}
contract REVLoansSourcedTests is TestBaseWorkflow, JBTest {
/// @notice the salts that are used to deploy the contracts.
bytes32 REV_DEPLOYER_SALT = "REVDeployer";
bytes32 ERC20_SALT = "REV_TOKEN";
REVDeployer REV_DEPLOYER;
JB721TiersHook EXAMPLE_HOOK;
/// @notice Deploys tiered ERC-721 hooks for revnets.
IJB721TiersHookDeployer HOOK_DEPLOYER;
IJB721TiersHookStore HOOK_STORE;
IJBAddressRegistry ADDRESS_REGISTRY;
IREVLoans LOANS_CONTRACT;
MockERC20 TOKEN;
/// @notice Deploys and tracks suckers for revnets.
IJBSuckerRegistry SUCKER_REGISTRY;
CTPublisher PUBLISHER;
uint256 FEE_PROJECT_ID;
uint256 REVNET_ID;
address USER = makeAddr("user");
/// @notice The address that is allowed to forward calls.
address private constant TRUSTED_FORWARDER = 0xB2b5841DBeF766d4b521221732F9B618fCf34A87;
function getFeeProjectConfig() internal view returns (FeeProjectConfig memory) {
// Define constants
string memory name = "Revnet";
string memory symbol = "$REV";
string memory projectUri = "ipfs://QmNRHT91HcDgMcenebYX7rJigt77cgNcosvuhX21wkF3tx";
uint8 decimals = 18;
uint256 decimalMultiplier = 10 ** decimals;
// The tokens that the project accepts and stores.
JBAccountingContext[] memory accountingContextsToAccept = new JBAccountingContext[](2);
// Accept the chain's native currency through the multi terminal.
accountingContextsToAccept[0] = JBAccountingContext({
token: JBConstants.NATIVE_TOKEN,
decimals: 18,
currency: uint32(uint160(JBConstants.NATIVE_TOKEN))
});
// For the tests we need to allow these payments, otherwise other revnets can't pay a fee.
// IRL, this would be handled by a swap terminal.
accountingContextsToAccept[1] =
JBAccountingContext({token: address(TOKEN), decimals: 6, currency: uint32(uint160(address(TOKEN)))});
// The terminals that the project will accept funds through.
JBTerminalConfig[] memory terminalConfigurations = new JBTerminalConfig[](1);
terminalConfigurations[0] =
JBTerminalConfig({terminal: jbMultiTerminal(), accountingContextsToAccept: accountingContextsToAccept});
// The project's revnet stage configurations.
REVStageConfig[] memory stageConfigurations = new REVStageConfig[](3);
JBSplit[] memory splits = new JBSplit[](1);
splits[0].beneficiary = payable(multisig());
splits[0].percent = 10_000;
{
REVAutoIssuance[] memory issuanceConfs = new REVAutoIssuance[](1);
issuanceConfs[0] = REVAutoIssuance({
chainId: uint32(block.chainid),
count: uint104(70_000 * decimalMultiplier),
beneficiary: multisig()
});
stageConfigurations[0] = REVStageConfig({
startsAtOrAfter: uint40(block.timestamp),
autoIssuances: issuanceConfs,
splitPercent: 2000, // 20%
splits: splits,
initialIssuance: uint112(1000 * decimalMultiplier),
issuanceCutFrequency: 90 days,
issuanceCutPercent: JBConstants.MAX_WEIGHT_CUT_PERCENT / 2,
cashOutTaxRate: 6000, // 0.6
extraMetadata: 0
});
}
stageConfigurations[1] = REVStageConfig({
startsAtOrAfter: uint40(stageConfigurations[0].startsAtOrAfter + 720 days),
autoIssuances: new REVAutoIssuance[](0),
splitPercent: 2000, // 20%
initialIssuance: 0, // inherit from previous cycle.
splits: splits,
issuanceCutFrequency: 180 days,
issuanceCutPercent: JBConstants.MAX_WEIGHT_CUT_PERCENT / 2,
cashOutTaxRate: 1000, // 0.1
extraMetadata: 0
});
stageConfigurations[2] = REVStageConfig({
startsAtOrAfter: uint40(stageConfigurations[1].startsAtOrAfter + (20 * 365 days)),
autoIssuances: new REVAutoIssuance[](0),
splitPercent: 0,
initialIssuance: 1,
splits: splits,
issuanceCutFrequency: 0,
issuanceCutPercent: 0,
cashOutTaxRate: 6000, // 0.6
extraMetadata: 0
});
REVLoanSource[] memory _loanSources = new REVLoanSource[](0);
// The project's revnet configuration
REVConfig memory revnetConfiguration = REVConfig({
description: REVDescription(name, symbol, projectUri, ERC20_SALT),
baseCurrency: uint32(uint160(JBConstants.NATIVE_TOKEN)),
splitOperator: multisig(),
stageConfigurations: stageConfigurations,
loanSources: _loanSources,
loans: address(0)
});
// The project's buyback hook configuration.
REVBuybackPoolConfig[] memory buybackPoolConfigurations = new REVBuybackPoolConfig[](1);
buybackPoolConfigurations[0] = REVBuybackPoolConfig({
token: JBConstants.NATIVE_TOKEN,
fee: 10_000,
twapWindow: 2 days,
twapSlippageTolerance: 9000
});
REVBuybackHookConfig memory buybackHookConfiguration =
REVBuybackHookConfig({hook: IJBBuybackHook(address(0)), poolConfigurations: buybackPoolConfigurations});
return FeeProjectConfig({
configuration: revnetConfiguration,
terminalConfigurations: terminalConfigurations,
buybackHookConfiguration: buybackHookConfiguration,
suckerDeploymentConfiguration: REVSuckerDeploymentConfig({
deployerConfigurations: new JBSuckerDeployerConfig[](0),
salt: keccak256(abi.encodePacked("REV"))
})
});
}
function getSecondProjectConfig() internal view returns (FeeProjectConfig memory) {
// Define constants
string memory name = "NANA";
string memory symbol = "$NANA";
string memory projectUri = "ipfs://QmNRHT91HcDgMcenebYX7rJigt77cgNxosvuhX21wkF3tx";
uint8 decimals = 18;
uint256 decimalMultiplier = 10 ** decimals;
// The tokens that the project accepts and stores.
JBAccountingContext[] memory accountingContextsToAccept = new JBAccountingContext[](2);
// Accept the chain's native currency through the multi terminal.
accountingContextsToAccept[0] = JBAccountingContext({
token: JBConstants.NATIVE_TOKEN,
decimals: 18,
currency: uint32(uint160(JBConstants.NATIVE_TOKEN))
});
accountingContextsToAccept[1] =
JBAccountingContext({token: address(TOKEN), decimals: 6, currency: uint32(uint160(address(TOKEN)))});
// The terminals that the project will accept funds through.
JBTerminalConfig[] memory terminalConfigurations = new JBTerminalConfig[](1);
terminalConfigurations[0] =
JBTerminalConfig({terminal: jbMultiTerminal(), accountingContextsToAccept: accountingContextsToAccept});
JBSplit[] memory splits = new JBSplit[](1);
splits[0].beneficiary = payable(multisig());
splits[0].percent = 10_000;
// The project's revnet stage configurations.
REVStageConfig[] memory stageConfigurations = new REVStageConfig[](3);
{
REVAutoIssuance[] memory issuanceConfs = new REVAutoIssuance[](1);
issuanceConfs[0] = REVAutoIssuance({
chainId: uint32(block.chainid),
count: uint104(70_000 * decimalMultiplier),
beneficiary: multisig()
});
stageConfigurations[0] = REVStageConfig({
startsAtOrAfter: uint40(block.timestamp),
autoIssuances: issuanceConfs,
splitPercent: 2000, // 20%
splits: splits,
initialIssuance: uint112(1000 * decimalMultiplier),
issuanceCutFrequency: 90 days,
issuanceCutPercent: JBConstants.MAX_WEIGHT_CUT_PERCENT / 2,
cashOutTaxRate: 0,
extraMetadata: 0
});
}
stageConfigurations[1] = REVStageConfig({
startsAtOrAfter: uint40(stageConfigurations[0].startsAtOrAfter + 720 days),
autoIssuances: new REVAutoIssuance[](0),
splitPercent: 2000, // 20%
splits: splits,
initialIssuance: 0, // inherit from previous cycle.
issuanceCutFrequency: 180 days,
issuanceCutPercent: JBConstants.MAX_WEIGHT_CUT_PERCENT / 2,
cashOutTaxRate: 0,
extraMetadata: 0
});
stageConfigurations[2] = REVStageConfig({
startsAtOrAfter: uint40(stageConfigurations[1].startsAtOrAfter + (20 * 365 days)),
autoIssuances: new REVAutoIssuance[](0),
splitPercent: 0,
splits: splits,
initialIssuance: 1, // this is a special number that is as close to max price as we can get.
issuanceCutFrequency: 0,
issuanceCutPercent: 0,
cashOutTaxRate: 0,
extraMetadata: 0
});
REVLoanSource[] memory _loanSources = new REVLoanSource[](2);
_loanSources[0] = REVLoanSource({token: JBConstants.NATIVE_TOKEN, terminal: jbMultiTerminal()});
_loanSources[1] = REVLoanSource({token: address(TOKEN), terminal: jbMultiTerminal()});
// The project's revnet configuration
REVConfig memory revnetConfiguration = REVConfig({
description: REVDescription(name, symbol, projectUri, "NANA_TOKEN"),
baseCurrency: uint32(uint160(JBConstants.NATIVE_TOKEN)),
splitOperator: multisig(),
stageConfigurations: stageConfigurations,
loanSources: _loanSources,
loans: address(LOANS_CONTRACT)
});
// The project's buyback hook configuration.
REVBuybackPoolConfig[] memory buybackPoolConfigurations = new REVBuybackPoolConfig[](1);
buybackPoolConfigurations[0] = REVBuybackPoolConfig({
token: JBConstants.NATIVE_TOKEN,
fee: 10_000,
twapWindow: 2 days,
twapSlippageTolerance: 9000
});
REVBuybackHookConfig memory buybackHookConfiguration =
REVBuybackHookConfig({hook: IJBBuybackHook(address(0)), poolConfigurations: buybackPoolConfigurations});
return FeeProjectConfig({
configuration: revnetConfiguration,
terminalConfigurations: terminalConfigurations,
buybackHookConfiguration: buybackHookConfiguration,
suckerDeploymentConfiguration: REVSuckerDeploymentConfig({
deployerConfigurations: new JBSuckerDeployerConfig[](0),
salt: keccak256(abi.encodePacked("NANA"))
})
});
}
function setUp() public override {
super.setUp();
FEE_PROJECT_ID = jbProjects().createFor(multisig());
SUCKER_REGISTRY = new JBSuckerRegistry(jbDirectory(), jbPermissions(), multisig(), address(0));
HOOK_STORE = new JB721TiersHookStore();
EXAMPLE_HOOK = new JB721TiersHook(jbDirectory(), jbPermissions(), jbRulesets(), HOOK_STORE, multisig());
ADDRESS_REGISTRY = new JBAddressRegistry();
HOOK_DEPLOYER = new JB721TiersHookDeployer(EXAMPLE_HOOK, HOOK_STORE, ADDRESS_REGISTRY, multisig());
PUBLISHER = new CTPublisher(jbController(), jbPermissions(), FEE_PROJECT_ID, multisig());
TOKEN = new MockERC20("1/2 ETH", "1/2");
// Configure a price feed for ETH/TOKEN.
// The token is worth 50% of the price of ETH.
MockPriceFeed priceFeed = new MockPriceFeed(1e21, 6);
vm.label(address(priceFeed), "Token:Eth/PriceFeed");
// Configure the price feed for the pair.
vm.prank(multisig());
jbPrices().addPriceFeedFor(
0, uint32(uint160(address(TOKEN))), uint32(uint160(JBConstants.NATIVE_TOKEN)), priceFeed
);
REV_DEPLOYER = new REVDeployer{salt: REV_DEPLOYER_SALT}(
jbController(), SUCKER_REGISTRY, FEE_PROJECT_ID, HOOK_DEPLOYER, PUBLISHER, TRUSTED_FORWARDER
);
LOANS_CONTRACT = new REVLoans({
revnets: REV_DEPLOYER,
revId: FEE_PROJECT_ID,
owner: address(this),
permit2: permit2(),
trustedForwarder: TRUSTED_FORWARDER
});
// Approve the basic deployer to configure the project.
vm.prank(address(multisig()));
jbProjects().approve(address(REV_DEPLOYER), FEE_PROJECT_ID);
// Build the config.
FeeProjectConfig memory feeProjectConfig = getFeeProjectConfig();
vm.prank(address(multisig()));
// Configure the project.
REV_DEPLOYER.deployFor({
revnetId: FEE_PROJECT_ID, // Zero to deploy a new revnet
configuration: feeProjectConfig.configuration,
terminalConfigurations: feeProjectConfig.terminalConfigurations,
buybackHookConfiguration: feeProjectConfig.buybackHookConfiguration,
suckerDeploymentConfiguration: feeProjectConfig.suckerDeploymentConfiguration
});
// Configure second revnet
FeeProjectConfig memory fee2Config = getSecondProjectConfig();
// Configure the project.
REVNET_ID = REV_DEPLOYER.deployFor({
revnetId: 0, // Zero to deploy a new revnet
configuration: fee2Config.configuration,
terminalConfigurations: fee2Config.terminalConfigurations,
buybackHookConfiguration: fee2Config.buybackHookConfiguration,
suckerDeploymentConfiguration: fee2Config.suckerDeploymentConfiguration
});
// Give Eth for the user experience
vm.deal(USER, 100e18);
}
function test_Pay_ERC20_Borrow_With_Loan_Source(uint256 payableAmount, uint32 prepaidFee) public {
vm.assume(payableAmount > 0 && payableAmount <= type(uint112).max);
vm.assume(
LOANS_CONTRACT.MIN_PREPAID_FEE_PERCENT() <= prepaidFee
&& prepaidFee <= LOANS_CONTRACT.MAX_PREPAID_FEE_PERCENT()
);
// Calculate the duration based upon the prepaidFee.
uint32 duration = uint32(mulDiv(3650 days, prepaidFee, LOANS_CONTRACT.MAX_PREPAID_FEE_PERCENT()));
// Deal the user some tokens.
deal(address(TOKEN), USER, payableAmount);
// Approve the terminal to spend the tokens.
vm.prank(USER);
TOKEN.approve(address(jbMultiTerminal()), payableAmount);
vm.prank(USER);
uint256 tokens = jbMultiTerminal().pay(REVNET_ID, address(TOKEN), payableAmount, USER, 0, "", "");
uint256 loanable = LOANS_CONTRACT.borrowableAmountFrom(REVNET_ID, tokens, 6, uint32(uint160(address(TOKEN))));
// If there is no loanable amount, we can't continue.
vm.assume(loanable > 0);
// User must give the loans contract permission, similar to an "approve" call, we're just spoofing to save time.
mockExpect(
address(jbPermissions()),
abi.encodeCall(IJBPermissions.hasPermission, (address(LOANS_CONTRACT), USER, 2, 10, true, true)),
abi.encode(true)
);
REVLoanSource memory sauce = REVLoanSource({token: address(TOKEN), terminal: jbMultiTerminal()});
vm.prank(USER);
(uint256 newLoanId,) = LOANS_CONTRACT.borrowFrom(REVNET_ID, sauce, loanable, tokens, payable(USER), prepaidFee);
REVLoan memory loan = LOANS_CONTRACT.loanOf(newLoanId);
assertEq(loan.amount, loanable);
assertEq(loan.collateral, tokens);
assertEq(loan.createdAt, block.timestamp);
assertEq(loan.prepaidFeePercent, prepaidFee);
assertEq(loan.prepaidDuration, duration);
assertEq(loan.source.token, address(TOKEN));
assertEq(address(loan.source.terminal), address(jbMultiTerminal()));
// Ensure loans contract isn't hodling
assertEq(TOKEN.balanceOf(address(LOANS_CONTRACT)), 0);
// The fees to be paid to NANA.
uint256 allowance_fees = JBFees.feeAmountFrom({amountBeforeFee: loanable, feePercent: jbMultiTerminal().FEE()});
// The fees to be paid to REV.
uint256 rev_fees =
JBFees.feeAmountFrom({amountBeforeFee: loanable, feePercent: LOANS_CONTRACT.REV_PREPAID_FEE_PERCENT()});
// The fees to be paid to the Project we are taking a loan from.
uint256 source_fees = JBFees.feeAmountFrom({amountBeforeFee: loanable, feePercent: prepaidFee});
uint256 fees = allowance_fees + rev_fees + source_fees;
// Ensure we actually received the token from the borrow
// Subtract the fee for REV and for the source revnet.
assertEq(TOKEN.balanceOf(address(USER)), loanable - fees);
}
function test_Cashout(
bool useNative,
uint104 autoIssuance,
uint256 totalSupplyExcludingAutoMint,
uint256 nativeSurplus,
uint256 tokensToCashout,
uint16 cashOutTaxRate
)
public
{
// Since we don't actually mint the autoIssuance tokens, we don't have to worry about it exceeding the
// `SafeSupply`.
vm.assume(cashOutTaxRate <= JBConstants.MAX_FEE);
vm.assume(totalSupplyExcludingAutoMint > 0 && totalSupplyExcludingAutoMint <= type(uint208).max);
vm.assume(nativeSurplus <= type(uint104).max);
vm.assume(totalSupplyExcludingAutoMint > tokensToCashout);
address token = useNative ? JBConstants.NATIVE_TOKEN : address(TOKEN);
// Deploy a new REVNET, that has multiple stages where the fee decrease.
// This lets people refinance their loans to get a better rate.
uint256 revnetProjectId;
{
FeeProjectConfig memory projectConfig = getSecondProjectConfig();
REVAutoIssuance[] memory issuanceConfs;
issuanceConfs = new REVAutoIssuance[](1);
issuanceConfs[0] =
REVAutoIssuance({chainId: uint32(block.chainid), count: uint104(autoIssuance), beneficiary: multisig()});
JBSplit[] memory splits = new JBSplit[](1);
splits[0].beneficiary = payable(multisig());
splits[0].percent = 10_000;
REVStageConfig[] memory stageConfigurations = new REVStageConfig[](1);
stageConfigurations[0] = REVStageConfig({
startsAtOrAfter: uint40(block.timestamp),
autoIssuances: issuanceConfs,
splitPercent: 2000, // 20%
splits: splits,
initialIssuance: 1000e18,
issuanceCutFrequency: 90 days,
issuanceCutPercent: JBConstants.MAX_WEIGHT_CUT_PERCENT / 2,
cashOutTaxRate: cashOutTaxRate, // 20%
extraMetadata: 0
});
// Replace the configuration.
projectConfig.configuration.stageConfigurations = stageConfigurations;
projectConfig.configuration.description.salt = "FeeChange";
revnetProjectId = REV_DEPLOYER.deployFor({
revnetId: 0, // Zero to deploy a new revnet
configuration: projectConfig.configuration,
terminalConfigurations: projectConfig.terminalConfigurations,
buybackHookConfiguration: projectConfig.buybackHookConfiguration,
suckerDeploymentConfiguration: projectConfig.suckerDeploymentConfiguration
});
}
// Add the surplus into the project.
if (useNative) {
vm.deal(USER, nativeSurplus);
} else {
deal(address(TOKEN), USER, nativeSurplus);
// Give allowance to spend our tokens.
vm.prank(USER);
TOKEN.approve(address(jbMultiTerminal()), nativeSurplus);
}
vm.prank(USER);
jbMultiTerminal().addToBalanceOf{value: useNative ? nativeSurplus : 0}(
revnetProjectId, token, nativeSurplus, false, string(""), bytes("")
);
// Mint the entire supply excluding automint to the user.
vm.prank(address(jbController()));
jbTokens().mintFor(USER, revnetProjectId, totalSupplyExcludingAutoMint);
// Check what a borrow would result in more.
uint256 loanable = LOANS_CONTRACT.borrowableAmountFrom(
revnetProjectId, tokensToCashout, useNative ? 18 : 6, uint32(uint160(token))
);
uint256 fullReclaimableSurplus = jbMultiTerminal().STORE().currentReclaimableSurplusOf({
projectId: revnetProjectId,
tokenCount: tokensToCashout,
totalSupply: totalSupplyExcludingAutoMint,
surplus: nativeSurplus
});
assertGe(fullReclaimableSurplus, loanable);
uint256 feeTokenCount =
cashOutTaxRate == 0 ? 0 : mulDiv(tokensToCashout, jbMultiTerminal().FEE(), JBConstants.MAX_FEE);
uint256 reclaimableSurplus = jbMultiTerminal().STORE().currentReclaimableSurplusOf({
projectId: revnetProjectId,
tokenCount: tokensToCashout - feeTokenCount,
totalSupply: totalSupplyExcludingAutoMint,
surplus: nativeSurplus
});
// In the `revFee` calculation we decrease the `nativeSurplus` by the `reclaimableSurplus`
// but due to a `stack too deep` we can't do that there, so we decrease it here.
// This is not the correct value for this variable, however in `revFee` is the last time we use this variable.
nativeSurplus -= reclaimableSurplus;
uint256 revFee = jbMultiTerminal().STORE().currentReclaimableSurplusOf({
projectId: revnetProjectId,
tokenCount: feeTokenCount,
totalSupply: totalSupplyExcludingAutoMint - (tokensToCashout - feeTokenCount),
surplus: nativeSurplus
});
assertGe(fullReclaimableSurplus, mulDiv((reclaimableSurplus + revFee), 995, 1000)); // small marging for curve
// rounding.
uint256 balanceBefore = _balanceOf(token, USER);
// Ensure that the hook was called.
vm.expectCall(address(REV_DEPLOYER), abi.encode(REVDeployer.beforeCashOutRecordedWith.selector));
// It only adds itself as a `after` cashoutHook if there is a cashout tax rate.
if (cashOutTaxRate > 0) {
vm.expectCall(address(REV_DEPLOYER), abi.encode(REVDeployer.afterCashOutRecordedWith.selector));
}
// Perform a cashout.
vm.prank(USER);
jbMultiTerminal().cashOutTokensOf(USER, revnetProjectId, tokensToCashout, token, 0, payable(USER), bytes(""));
// Make sure the contracts do not accidentally hold any tokens.
assertEq(_balanceOf(token, address(REV_DEPLOYER)), 0);
assertEq(_balanceOf(token, address(LOANS_CONTRACT)), 0);
// make sure the user has received tokens.
assertGe(_balanceOf(token, USER), balanceBefore);
uint256 balance = _balanceOf(token, USER) - balanceBefore;
uint256 nanaFee = cashOutTaxRate == 0
? 0
: JBFees.feeAmountResultingIn({amountAfterFee: balance, feePercent: jbMultiTerminal().FEE()});
assertApproxEqAbs(balance, reclaimableSurplus - nanaFee, 1);
assertGe(reclaimableSurplus + revFee, mulDiv(loanable, 97, 100)); // small marging for curve rounding.
}
function test_Pay_Borrow_With_Loan_Source() public {
vm.prank(USER);
uint256 tokens = jbMultiTerminal().pay{value: 1e18}(REVNET_ID, JBConstants.NATIVE_TOKEN, 1e18, USER, 0, "", "");
uint256 loanable =
LOANS_CONTRACT.borrowableAmountFrom(REVNET_ID, tokens, 18, uint32(uint160(JBConstants.NATIVE_TOKEN)));
assertGt(loanable, 0);
// User must give the loans contract permission, similar to an "approve" call, we're just spoofing to save time.
mockExpect(
address(jbPermissions()),
abi.encodeCall(IJBPermissions.hasPermission, (address(LOANS_CONTRACT), USER, 2, 10, true, true)),
abi.encode(true)
);
REVLoanSource memory sauce = REVLoanSource({token: JBConstants.NATIVE_TOKEN, terminal: jbMultiTerminal()});
// Check the balance of the user before the borrow.
uint256 balanceBefore = USER.balance;
vm.prank(USER);
(uint256 newLoanId,) = LOANS_CONTRACT.borrowFrom(REVNET_ID, sauce, loanable, tokens, payable(USER), 500);
REVLoan memory loan = LOANS_CONTRACT.loanOf(newLoanId);
assertEq(loan.amount, loanable);
assertEq(loan.collateral, tokens);
assertEq(loan.createdAt, block.timestamp);
assertEq(loan.prepaidFeePercent, 500);
assertEq(loan.prepaidDuration, mulDiv(500, 3650 days, 500));
assertEq(loan.source.token, JBConstants.NATIVE_TOKEN);
assertEq(address(loan.source.terminal), address(jbMultiTerminal()));
// Ensure loans contract isn't hodling
assertEq(address(LOANS_CONTRACT).balance, 0);
// Ensure we actually received ETH from the borrow
assertGt(USER.balance - balanceBefore, 0);
}
function testFuzz_Pay_Borrow_PayOff_With_Loan_Source(
uint256 percentOfCollateralToRemove,
uint256 prepaidFeePercent,
uint256 daysToWarp
)
public
{
///
percentOfCollateralToRemove = bound(percentOfCollateralToRemove, 0, 10_000);
prepaidFeePercent = bound(prepaidFeePercent, 25, 500);
daysToWarp = bound(daysToWarp, 0, 3650);
daysToWarp = daysToWarp * 1 days;
vm.prank(USER);
uint256 tokens = jbMultiTerminal().pay{value: 1e18}(REVNET_ID, JBConstants.NATIVE_TOKEN, 1e18, USER, 0, "", "");
uint256 loanable =
LOANS_CONTRACT.borrowableAmountFrom(REVNET_ID, tokens, 18, uint32(uint160(JBConstants.NATIVE_TOKEN)));
assertGt(loanable, 0);
// User must give the loans contract permission, similar to an "approve" call, we're just spoofing to save time.
mockExpect(
address(jbPermissions()),
abi.encodeCall(IJBPermissions.hasPermission, (address(LOANS_CONTRACT), USER, 2, 10, true, true)),
abi.encode(true)
);
uint256 newLoanId;
{
REVLoanSource memory sauce = REVLoanSource({token: JBConstants.NATIVE_TOKEN, terminal: jbMultiTerminal()});
vm.prank(USER);
(newLoanId,) =
LOANS_CONTRACT.borrowFrom(REVNET_ID, sauce, loanable, tokens, payable(USER), prepaidFeePercent);
}
REVLoan memory loan = LOANS_CONTRACT.loanOf(newLoanId);
assertEq(loan.amount, loanable);
assertEq(loan.collateral, tokens);
assertEq(loan.createdAt, block.timestamp);
assertEq(loan.prepaidFeePercent, prepaidFeePercent);
assertEq(loan.prepaidDuration, mulDiv(prepaidFeePercent, 3650 days, 500));
assertEq(loan.source.token, JBConstants.NATIVE_TOKEN);
assertEq(address(loan.source.terminal), address(jbMultiTerminal()));
// warp forward
vm.warp(block.timestamp + daysToWarp);
uint256 collateralReturned = mulDiv(loan.collateral, percentOfCollateralToRemove, 10_000);
uint256 newCollateral = loan.collateral - collateralReturned;
uint256 borrowableFromNewCollateral =
LOANS_CONTRACT.borrowableAmountFrom(REVNET_ID, newCollateral, 18, uint32(uint160(JBConstants.NATIVE_TOKEN)));
uint256 amountDiff = borrowableFromNewCollateral > loan.amount ? 0 : loan.amount - borrowableFromNewCollateral;
uint256 maxAmountPaidDown = loan.amount;
// Calculate the fee.
{
// Keep a reference to the time since the loan was created.
uint256 timeSinceLoanCreated = block.timestamp - loan.createdAt;
// If the loan period has passed the prepaid time frame, take a fee.
if (timeSinceLoanCreated > loan.prepaidDuration) {
// Calculate the prepaid fee for the amount being paid back.
uint256 prepaidAmount =
JBFees.feeAmountFrom({amountBeforeFee: amountDiff, feePercent: loan.prepaidFeePercent});
// Calculate the fee as a linear proportion given the amount of time that has passed.
// sourceFeeAmount = mulDiv(amount, timeSinceLoanCreated, LOAN_LIQUIDATION_DURATION) - prepaidAmount;
maxAmountPaidDown += JBFees.feeAmountFrom({
amountBeforeFee: amountDiff - prepaidAmount,
feePercent: mulDiv(timeSinceLoanCreated, JBConstants.MAX_FEE, 3650 days)
});
}
}
// ensure we have the balance
vm.deal(USER, maxAmountPaidDown);
// empty allowance data
JBSingleAllowance memory allowance;
if (borrowableFromNewCollateral > loan.amount) {
vm.expectRevert(
abi.encodeWithSelector(
REVLoans.REVLoans_NewBorrowAmountGreaterThanLoanAmount.selector,
borrowableFromNewCollateral,
loan.amount
)
);
}
// call to pay-down the loan
vm.prank(USER);
(, REVLoan memory reducedLoan) = LOANS_CONTRACT.repayLoan{value: maxAmountPaidDown}(
newLoanId, maxAmountPaidDown, collateralReturned, payable(USER), allowance
);
if (borrowableFromNewCollateral > loan.amount) {
// End of the test, its not possible to `repay` a loan with such a small amount that the loan value goes up.
// The `collateralReturned` should be increased so the value of the loan goes down.
return;
}
assertApproxEqAbs(reducedLoan.amount, loan.amount - amountDiff, 1);
assertEq(reducedLoan.collateral, loan.collateral - collateralReturned);
assertEq(reducedLoan.createdAt, block.timestamp - daysToWarp);
assertEq(reducedLoan.prepaidFeePercent, prepaidFeePercent);
assertEq(reducedLoan.prepaidDuration, mulDiv(prepaidFeePercent, 3650 days, 500));
assertEq(reducedLoan.source.token, JBConstants.NATIVE_TOKEN);
assertEq(address(reducedLoan.source.terminal), address(jbMultiTerminal()));
}
function test_Refinance_Excess_Collateral() public {
// peform the auto issuance.
REV_DEPLOYER.autoIssueFor(REVNET_ID, block.timestamp, multisig());
vm.prank(USER);
uint256 tokens = jbMultiTerminal().pay{value: 1e18}(REVNET_ID, JBConstants.NATIVE_TOKEN, 1e18, USER, 0, "", "");
uint256 loanable =
LOANS_CONTRACT.borrowableAmountFrom(REVNET_ID, tokens, 18, uint32(uint160(JBConstants.NATIVE_TOKEN)));
assertGt(loanable, 0);
mockExpect(
address(jbPermissions()),
abi.encodeCall(IJBPermissions.hasPermission, (address(LOANS_CONTRACT), USER, 2, 10, true, true)),
abi.encode(true)
);
REVLoanSource memory sauce = REVLoanSource({token: JBConstants.NATIVE_TOKEN, terminal: jbMultiTerminal()});
vm.prank(USER);
(uint256 newLoanId,) = LOANS_CONTRACT.borrowFrom(REVNET_ID, sauce, loanable, tokens, payable(USER), 500);
REVLoan memory loan = LOANS_CONTRACT.loanOf(newLoanId);
// Ensure loans contract isn't hodling
assertEq(address(LOANS_CONTRACT).balance, 0);
// Ensure we actually received ETH from the borrow
assertGt(USER.balance, 100e18 - 1e18);
// get the updated loanableFrom the same amount as earlier
uint256 loanableSecondStage = LOANS_CONTRACT.borrowableAmountFrom(
REVNET_ID, loan.collateral, 18, uint32(uint160(JBConstants.NATIVE_TOKEN))
);
// loanable amount is slightly higher due to fee payment increasing the supply/assets ratio.
assertGt(loanableSecondStage, loanable);
// we should not have to add collateral
uint256 collateralToAdd = 0;
// this should be a 0.5% gain to be reallocated
uint256 collateralToTransfer = mulDiv(loan.collateral, 50, 10_000);
// get the new amount to borrow
uint256 newAmount = LOANS_CONTRACT.borrowableAmountFrom(
REVNET_ID, collateralToTransfer, 18, uint32(uint160(JBConstants.NATIVE_TOKEN))
);
uint256 userBalanceBefore = USER.balance;
vm.prank(USER);
(,, REVLoan memory adjustedLoan, REVLoan memory newLoan) = LOANS_CONTRACT.reallocateCollateralFromLoan(
newLoanId, collateralToTransfer, sauce, newAmount, collateralToAdd, payable(USER), 25
);
uint256 userBalanceAfter = USER.balance;
// check we received funds period
assertGt(userBalanceAfter, userBalanceBefore);
// check we received ~newAmount with a 0.1% buffer
assertApproxEqRel(userBalanceBefore + newLoan.amount, userBalanceAfter, 1e15);
// Check the old loan has been adjusted
assertEq(adjustedLoan.amount, loan.amount); // Should match the old loan
assertEq(adjustedLoan.collateral, loan.collateral - collateralToTransfer); // should be reduced
assertEq(adjustedLoan.createdAt, loan.createdAt); // Should match the old loan
assertEq(adjustedLoan.prepaidFeePercent, loan.prepaidFeePercent); // Should match the old loan
assertEq(adjustedLoan.prepaidDuration, mulDiv(loan.prepaidFeePercent, 3650 days, 500));
assertEq(adjustedLoan.source.token, JBConstants.NATIVE_TOKEN);
assertEq(address(adjustedLoan.source.terminal), address(jbMultiTerminal()));
// Check the new loan with the excess from refinancing
assertEq(newLoan.amount, newAmount); // Excess from reallocateCollateral
assertEq(newLoan.collateral, collateralToTransfer); // Matches the amount transferred
assertEq(newLoan.createdAt, block.timestamp);
assertEq(newLoan.prepaidFeePercent, 25); // Configured as 25 (min) in reallocateCollateral call
assertEq(newLoan.prepaidDuration, mulDiv(25, 3650 days, 500)); // Configured as 25 in reallocateCollateral call
assertEq(newLoan.source.token, JBConstants.NATIVE_TOKEN);
assertEq(address(newLoan.source.terminal), address(jbMultiTerminal()));
}
function test_Refinance_Not_Enough_Collateral() public {
// peform the auto issuance.
REV_DEPLOYER.autoIssueFor(REVNET_ID, block.timestamp, multisig());
vm.prank(USER);
uint256 tokens = jbMultiTerminal().pay{value: 1e18}(REVNET_ID, JBConstants.NATIVE_TOKEN, 1e18, USER, 0, "", "");
uint256 loanable =
LOANS_CONTRACT.borrowableAmountFrom(REVNET_ID, tokens, 18, uint32(uint160(JBConstants.NATIVE_TOKEN)));
assertGt(loanable, 0);
mockExpect(
address(jbPermissions()),
abi.encodeCall(IJBPermissions.hasPermission, (address(LOANS_CONTRACT), USER, 2, 10, true, true)),
abi.encode(true)
);
REVLoanSource memory sauce = REVLoanSource({token: JBConstants.NATIVE_TOKEN, terminal: jbMultiTerminal()});
vm.prank(USER);
(uint256 newLoanId,) = LOANS_CONTRACT.borrowFrom(REVNET_ID, sauce, loanable, tokens, payable(USER), 500);
REVLoan memory loan = LOANS_CONTRACT.loanOf(newLoanId);
// Ensure loans contract isn't hodling
assertEq(address(LOANS_CONTRACT).balance, 0);
// Ensure we actually received ETH from the borrow
assertGt(USER.balance, 100e18 - 1e18);
// get the updated loanableFrom the same amount as earlier
uint256 loanableSecondStage = LOANS_CONTRACT.borrowableAmountFrom(
REVNET_ID, loan.collateral, 18, uint32(uint160(JBConstants.NATIVE_TOKEN))
);
// loanable amount is slightly higher due to fee payment increasing the supply/assets ratio.
assertGt(loanableSecondStage, loanable);
// we should not have to add collateral
uint256 collateralToAdd = 0;
// this should be a 0.5% gain to be reallocated
uint256 collateralToTransfer = mulDiv(loan.collateral, 50, 10_000);
// get the new amount to borrow
uint256 newAmount = LOANS_CONTRACT.borrowableAmountFrom(
REVNET_ID, collateralToTransfer, 18, uint32(uint160(JBConstants.NATIVE_TOKEN))
);
vm.expectRevert(REVLoans.REVLoans_NotEnoughCollateral.selector);
vm.prank(USER);
LOANS_CONTRACT.reallocateCollateralFromLoan(
// collateral exceeds with + 1
newLoanId,
loan.collateral + 1,
sauce,
newAmount,
collateralToAdd,
payable(USER),
0
);
}
function test_Refinance_Unauthorized() public {
// peform the auto issuance.
REV_DEPLOYER.autoIssueFor(REVNET_ID, block.timestamp, multisig());
vm.prank(USER);
uint256 tokens = jbMultiTerminal().pay{value: 1e18}(REVNET_ID, JBConstants.NATIVE_TOKEN, 1e18, USER, 0, "", "");
uint256 loanable =
LOANS_CONTRACT.borrowableAmountFrom(REVNET_ID, tokens, 18, uint32(uint160(JBConstants.NATIVE_TOKEN)));
assertGt(loanable, 0);
mockExpect(
address(jbPermissions()),
abi.encodeCall(IJBPermissions.hasPermission, (address(LOANS_CONTRACT), USER, 2, 10, true, true)),
abi.encode(true)
);
REVLoanSource memory sauce = REVLoanSource({token: JBConstants.NATIVE_TOKEN, terminal: jbMultiTerminal()});
vm.prank(USER);
(uint256 newLoanId,) = LOANS_CONTRACT.borrowFrom(REVNET_ID, sauce, loanable, tokens, payable(USER), 500);
REVLoan memory loan = LOANS_CONTRACT.loanOf(newLoanId);
// Ensure loans contract isn't hodling
assertEq(address(LOANS_CONTRACT).balance, 0);
// Ensure we actually received ETH from the borrow
assertGt(USER.balance, 100e18 - 1e18);
// get the updated loanableFrom the same amount as earlier
uint256 loanableSecondStage = LOANS_CONTRACT.borrowableAmountFrom(
REVNET_ID, loan.collateral, 18, uint32(uint160(JBConstants.NATIVE_TOKEN))
);
// loanable amount is slightly higher due to fee payment increasing the supply/assets ratio.
assertGt(loanableSecondStage, loanable);
// we should not have to add collateral
uint256 collateralToAdd = 0;
// this should be a 0.5% gain to be reallocated
uint256 collateralToTransfer = mulDiv(loan.collateral, 50, 10_000);
// get the new amount to borrow
uint256 newAmount = LOANS_CONTRACT.borrowableAmountFrom(
REVNET_ID, collateralToTransfer, 18, uint32(uint160(JBConstants.NATIVE_TOKEN))
);
address unauthorized = address(1);
vm.expectRevert(abi.encodeWithSelector(REVLoans.REVLoans_Unauthorized.selector, unauthorized, USER));
vm.prank(unauthorized);
LOANS_CONTRACT.reallocateCollateralFromLoan(
newLoanId, collateralToTransfer, sauce, newAmount, collateralToAdd, payable(USER), 25
);
}
function test_BorrowWithFeeConverges() public {
vm.skip(true);
// Config
uint256 paymentPerBorrow = 0.2 ether;
uint16 cashOutTaxRate = 6000;
uint256 premint = 0;
uint256 amountPaidBeforeFirstBorrow = 0.5 ether;
// Deploy a new REVNET, that has multiple stages where the fee decrease.
// This lets people refinance their loans to get a better rate.
uint256 revnetProjectId;
{
FeeProjectConfig memory projectConfig = getSecondProjectConfig();
REVAutoIssuance[] memory issuanceConfs;
if (premint > 0) {
issuanceConfs = new REVAutoIssuance[](1);
issuanceConfs[0] =
REVAutoIssuance({chainId: uint32(block.chainid), count: uint104(premint), beneficiary: multisig()});
}
JBSplit[] memory splits = new JBSplit[](1);
splits[0].beneficiary = payable(multisig());
splits[0].percent = 10_000;
REVStageConfig[] memory stageConfigurations = new REVStageConfig[](1);
stageConfigurations[0] = REVStageConfig({
startsAtOrAfter: uint40(block.timestamp),
autoIssuances: new REVAutoIssuance[](0),
splitPercent: 0, // 20%
splits: splits,
initialIssuance: 1000e18,
issuanceCutFrequency: 180 days,
issuanceCutPercent: JBConstants.MAX_WEIGHT_CUT_PERCENT / 2,
cashOutTaxRate: cashOutTaxRate, // 20%
extraMetadata: 0
});
// Replace the configuration.
projectConfig.configuration.stageConfigurations = stageConfigurations;
projectConfig.configuration.description.salt = "FeeChange";
revnetProjectId = REV_DEPLOYER.deployFor({
revnetId: 0, // Zero to deploy a new revnet
configuration: projectConfig.configuration,
terminalConfigurations: projectConfig.terminalConfigurations,
buybackHookConfiguration: projectConfig.buybackHookConfiguration,
suckerDeploymentConfiguration: projectConfig.suckerDeploymentConfiguration
});
}
if (amountPaidBeforeFirstBorrow > 0) {
vm.deal(USER, amountPaidBeforeFirstBorrow);