@rev-net/core-v6 0.0.37 → 0.0.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/CHANGELOG.md +2 -2
  2. package/README.md +6 -7
  3. package/foundry.toml +1 -1
  4. package/package.json +23 -16
  5. package/references/operations.md +1 -1
  6. package/references/runtime.md +1 -1
  7. package/script/Deploy.s.sol +12 -9
  8. package/src/REVDeployer.sol +69 -67
  9. package/src/REVHiddenTokens.sol +2 -2
  10. package/src/REVLoans.sol +26 -22
  11. package/src/REVOwner.sol +147 -29
  12. package/src/interfaces/IREVDeployer.sol +2 -1
  13. package/src/interfaces/IREVHiddenTokens.sol +4 -1
  14. package/src/interfaces/IREVOwner.sol +5 -0
  15. package/src/structs/REVAutoIssuance.sol +4 -2
  16. package/src/structs/REVConfig.sol +8 -5
  17. package/src/structs/REVDescription.sol +6 -5
  18. package/src/structs/REVLoan.sol +8 -5
  19. package/src/structs/REVStageConfig.sol +14 -16
  20. package/ADMINISTRATION.md +0 -73
  21. package/ARCHITECTURE.md +0 -116
  22. package/AUDIT_INSTRUCTIONS.md +0 -90
  23. package/RISKS.md +0 -107
  24. package/SKILLS.md +0 -46
  25. package/STYLE_GUIDE.md +0 -610
  26. package/USER_JOURNEYS.md +0 -195
  27. package/foundry.lock +0 -11
  28. package/slither-ci.config.json +0 -10
  29. package/sphinx.lock +0 -507
  30. package/test/REV.integrations.t.sol +0 -573
  31. package/test/REVAutoIssuanceFuzz.t.sol +0 -328
  32. package/test/REVDeployerRegressions.t.sol +0 -396
  33. package/test/REVInvincibility.t.sol +0 -1371
  34. package/test/REVInvincibilityHandler.sol +0 -387
  35. package/test/REVLifecycle.t.sol +0 -420
  36. package/test/REVLoans.invariants.t.sol +0 -724
  37. package/test/REVLoansAttacks.t.sol +0 -816
  38. package/test/REVLoansFeeRecovery.t.sol +0 -783
  39. package/test/REVLoansFindings.t.sol +0 -711
  40. package/test/REVLoansRegressions.t.sol +0 -364
  41. package/test/REVLoansSourceFeeRecovery.t.sol +0 -517
  42. package/test/REVLoansSourced.t.sol +0 -1839
  43. package/test/REVLoansUnSourced.t.sol +0 -409
  44. package/test/TestAuditFixVerification.t.sol +0 -675
  45. package/test/TestBurnHeldTokens.t.sol +0 -394
  46. package/test/TestCEIPattern.t.sol +0 -508
  47. package/test/TestCashOutCallerValidation.t.sol +0 -452
  48. package/test/TestConversionDocumentation.t.sol +0 -365
  49. package/test/TestCrossCurrencyReclaim.t.sol +0 -610
  50. package/test/TestCrossSourceReallocation.t.sol +0 -361
  51. package/test/TestERC2771MetaTx.t.sol +0 -585
  52. package/test/TestEmptyBuybackSpecs.t.sol +0 -300
  53. package/test/TestFlashLoanSurplus.t.sol +0 -365
  54. package/test/TestHiddenTokens.t.sol +0 -474
  55. package/test/TestHookArrayOOB.t.sol +0 -278
  56. package/test/TestLiquidationBehavior.t.sol +0 -398
  57. package/test/TestLoanSourceRotation.t.sol +0 -553
  58. package/test/TestLoansCashOutDelay.t.sol +0 -493
  59. package/test/TestLongTailEconomics.t.sol +0 -677
  60. package/test/TestLowFindings.t.sol +0 -677
  61. package/test/TestMixedFixes.t.sol +0 -593
  62. package/test/TestPermit2Signatures.t.sol +0 -683
  63. package/test/TestReallocationSandwich.t.sol +0 -412
  64. package/test/TestRevnetRegressions.t.sol +0 -350
  65. package/test/TestSplitWeightAdjustment.t.sol +0 -527
  66. package/test/TestSplitWeightE2E.t.sol +0 -605
  67. package/test/TestSplitWeightFork.t.sol +0 -855
  68. package/test/TestStageTransitionBorrowable.t.sol +0 -301
  69. package/test/TestSwapTerminalPermission.t.sol +0 -262
  70. package/test/TestTerminalEncodingInHash.t.sol +0 -326
  71. package/test/TestUint112Overflow.t.sol +0 -311
  72. package/test/TestZeroAmountLoanGuard.t.sol +0 -378
  73. package/test/TestZeroRepayment.t.sol +0 -354
  74. package/test/audit/CrossChainBuybackRouteMismatch.t.sol +0 -184
  75. package/test/audit/HiddenSupplyCashout.t.sol +0 -61
  76. package/test/audit/LoanIdOverflowGuard.t.sol +0 -523
  77. package/test/audit/NemesisVerification.t.sol +0 -97
  78. package/test/audit/OperatorDelegation.t.sol +0 -356
  79. package/test/audit/PhantomSurplusTerminal.t.sol +0 -367
  80. package/test/audit/REVOwnerCurrencyMismatch.t.sol +0 -188
  81. package/test/audit/REVOwnerRemoteSurplusCurrencyMismatch.t.sol +0 -140
  82. package/test/audit/ReallocatePermission.t.sol +0 -363
  83. package/test/audit/RemoteLoanAccountingGap.t.sol +0 -74
  84. package/test/audit/SupportsInterfaceTest.t.sol +0 -51
  85. package/test/audit/TestFeeAllowanceLeak.t.sol +0 -197
  86. package/test/audit/TestLoansAndDeployerFixes.t.sol +0 -576
  87. package/test/fork/ForkTestBase.sol +0 -727
  88. package/test/fork/TestAutoIssuanceFork.t.sol +0 -148
  89. package/test/fork/TestCashOutFork.t.sol +0 -253
  90. package/test/fork/TestIssuanceDecayFork.t.sol +0 -158
  91. package/test/fork/TestLoanAdversarialFork.t.sol +0 -744
  92. package/test/fork/TestLoanBorrowFork.t.sol +0 -163
  93. package/test/fork/TestLoanCrossRulesetFork.t.sol +0 -308
  94. package/test/fork/TestLoanERC20Fork.t.sol +0 -459
  95. package/test/fork/TestLoanLiquidationFork.t.sol +0 -135
  96. package/test/fork/TestLoanReallocateFork.t.sol +0 -113
  97. package/test/fork/TestLoanRepayFork.t.sol +0 -188
  98. package/test/fork/TestLoanTransferFork.t.sol +0 -143
  99. package/test/fork/TestPermit2PaymentFork.t.sol +0 -300
  100. package/test/fork/TestSplitWeightFork.t.sol +0 -189
  101. package/test/helpers/MaliciousContracts.sol +0 -247
  102. package/test/helpers/REVEmpty721Config.sol +0 -45
  103. package/test/mock/MockBuybackCashOutRecorder.sol +0 -84
  104. package/test/mock/MockBuybackDataHook.sol +0 -112
  105. package/test/mock/MockBuybackDataHookMintPath.sol +0 -68
  106. package/test/mock/MockSuckerRegistry.sol +0 -17
  107. package/test/regression/TestBurnPermissionRequired.t.sol +0 -294
  108. package/test/regression/TestCashOutBuybackFeeLeak.t.sol +0 -232
  109. package/test/regression/TestCrossRevnetLiquidation.t.sol +0 -255
  110. package/test/regression/TestCumulativeLoanCounter.t.sol +0 -361
  111. package/test/regression/TestLiquidateGapHandling.t.sol +0 -394
  112. package/test/regression/TestZeroPriceFeed.t.sol +0 -422
@@ -1,593 +0,0 @@
1
- // SPDX-License-Identifier: MIT
2
- pragma solidity 0.8.28;
3
-
4
- // forge-lint: disable-next-line(unaliased-plain-import)
5
- import "forge-std/Test.sol";
6
- // forge-lint: disable-next-line(unaliased-plain-import)
7
- import /* {*} from */ "@bananapus/core-v6/test/helpers/TestBaseWorkflow.sol";
8
- // import /* {*} from "@bananapus/721-hook-v6/src/JB721TiersHookDeployer.sol";
9
- // forge-lint: disable-next-line(unaliased-plain-import)
10
- import /* {*} from */ "./../src/REVDeployer.sol";
11
- // forge-lint: disable-next-line(unaliased-plain-import)
12
- import "@croptop/core-v6/src/CTPublisher.sol";
13
- import {MockBuybackDataHook} from "./mock/MockBuybackDataHook.sol";
14
- // forge-lint: disable-next-line(unaliased-plain-import)
15
- import "@bananapus/core-v6/script/helpers/CoreDeploymentLib.sol";
16
- // forge-lint: disable-next-line(unaliased-plain-import)
17
- import "@bananapus/721-hook-v6/script/helpers/Hook721DeploymentLib.sol";
18
- // forge-lint: disable-next-line(unaliased-plain-import)
19
- import "@bananapus/suckers-v6/script/helpers/SuckerDeploymentLib.sol";
20
- // forge-lint: disable-next-line(unaliased-plain-import)
21
- import "@croptop/core-v6/script/helpers/CroptopDeploymentLib.sol";
22
- // forge-lint: disable-next-line(unaliased-plain-import)
23
- import "@bananapus/router-terminal-v6/script/helpers/RouterTerminalDeploymentLib.sol";
24
- import {JBConstants} from "@bananapus/core-v6/src/libraries/JBConstants.sol";
25
- import {JBAccountingContext} from "@bananapus/core-v6/src/structs/JBAccountingContext.sol";
26
- import {MockPriceFeed} from "@bananapus/core-v6/test/mock/MockPriceFeed.sol";
27
- import {MockERC20} from "@bananapus/core-v6/test/mock/MockERC20.sol";
28
- import {REVLoans} from "../src/REVLoans.sol";
29
- import {REVLoan} from "../src/structs/REVLoan.sol";
30
- import {REVStageConfig, REVAutoIssuance} from "../src/structs/REVStageConfig.sol";
31
- import {REVLoanSource} from "../src/structs/REVLoanSource.sol";
32
- import {REVDescription} from "../src/structs/REVDescription.sol";
33
- import {JBSuckerDeployerConfig} from "@bananapus/suckers-v6/src/structs/JBSuckerDeployerConfig.sol";
34
- import {JBSuckerRegistry} from "@bananapus/suckers-v6/src/JBSuckerRegistry.sol";
35
- import {JB721TiersHookDeployer} from "@bananapus/721-hook-v6/src/JB721TiersHookDeployer.sol";
36
- import {JB721TiersHook} from "@bananapus/721-hook-v6/src/JB721TiersHook.sol";
37
- import {JB721TiersHookStore} from "@bananapus/721-hook-v6/src/JB721TiersHookStore.sol";
38
- import {JB721CheckpointsDeployer} from "@bananapus/721-hook-v6/src/JB721CheckpointsDeployer.sol";
39
- import {IJB721CheckpointsDeployer} from "@bananapus/721-hook-v6/src/interfaces/IJB721CheckpointsDeployer.sol";
40
- import {JBAddressRegistry} from "@bananapus/address-registry-v6/src/JBAddressRegistry.sol";
41
- import {IJBAddressRegistry} from "@bananapus/address-registry-v6/src/interfaces/IJBAddressRegistry.sol";
42
- import {REVEmpty721Config} from "./helpers/REVEmpty721Config.sol";
43
- import {REVOwner} from "../src/REVOwner.sol";
44
- import {IREVDeployer} from "../src/interfaces/IREVDeployer.sol";
45
- import {MockSuckerRegistry} from "./mock/MockSuckerRegistry.sol";
46
-
47
- /// @notice Tests for PR #32: liquidation boundary, reallocate msg.value, and decimal normalization fixes.
48
- contract TestMixedFixes is TestBaseWorkflow {
49
- // forge-lint: disable-next-line(mixed-case-variable)
50
- bytes32 REV_DEPLOYER_SALT = "REVDeployer";
51
-
52
- // forge-lint: disable-next-line(mixed-case-variable)
53
- REVDeployer REV_DEPLOYER;
54
- // forge-lint: disable-next-line(mixed-case-variable)
55
- REVOwner REV_OWNER;
56
- // forge-lint: disable-next-line(mixed-case-variable)
57
- JB721TiersHook EXAMPLE_HOOK;
58
- // forge-lint: disable-next-line(mixed-case-variable)
59
- IJB721TiersHookDeployer HOOK_DEPLOYER;
60
- // forge-lint: disable-next-line(mixed-case-variable)
61
- IJB721TiersHookStore HOOK_STORE;
62
- // forge-lint: disable-next-line(mixed-case-variable)
63
- IJBAddressRegistry ADDRESS_REGISTRY;
64
- // forge-lint: disable-next-line(mixed-case-variable)
65
- REVLoans LOANS_CONTRACT;
66
- // forge-lint: disable-next-line(mixed-case-variable)
67
- MockERC20 TOKEN;
68
- // forge-lint: disable-next-line(mixed-case-variable)
69
- IJBSuckerRegistry SUCKER_REGISTRY;
70
- // forge-lint: disable-next-line(mixed-case-variable)
71
- CTPublisher PUBLISHER;
72
- // forge-lint: disable-next-line(mixed-case-variable)
73
- MockBuybackDataHook MOCK_BUYBACK;
74
-
75
- // forge-lint: disable-next-line(mixed-case-variable)
76
- uint256 FEE_PROJECT_ID;
77
- // forge-lint: disable-next-line(mixed-case-variable)
78
- uint256 REVNET_ID;
79
-
80
- // forge-lint: disable-next-line(mixed-case-variable)
81
- address USER = makeAddr("user");
82
-
83
- address private constant TRUSTED_FORWARDER = 0xB2b5841DBeF766d4b521221732F9B618fCf34A87;
84
-
85
- function setUp() public override {
86
- super.setUp();
87
- FEE_PROJECT_ID = jbProjects().createFor(multisig());
88
- SUCKER_REGISTRY = new JBSuckerRegistry(jbDirectory(), jbPermissions(), multisig(), address(0));
89
- HOOK_STORE = new JB721TiersHookStore();
90
- EXAMPLE_HOOK = new JB721TiersHook(
91
- jbDirectory(),
92
- jbPermissions(),
93
- jbPrices(),
94
- jbRulesets(),
95
- HOOK_STORE,
96
- jbSplits(),
97
- IJB721CheckpointsDeployer(address(new JB721CheckpointsDeployer())),
98
- multisig()
99
- );
100
- ADDRESS_REGISTRY = new JBAddressRegistry();
101
- HOOK_DEPLOYER = new JB721TiersHookDeployer(EXAMPLE_HOOK, HOOK_STORE, ADDRESS_REGISTRY, multisig());
102
- PUBLISHER = new CTPublisher(jbDirectory(), jbPermissions(), FEE_PROJECT_ID, multisig());
103
- MOCK_BUYBACK = new MockBuybackDataHook();
104
- TOKEN = new MockERC20("1/2 ETH", "1/2");
105
- MockPriceFeed priceFeed = new MockPriceFeed(1e21, 6);
106
- vm.prank(multisig());
107
- jbPrices()
108
- .addPriceFeedFor(0, uint32(uint160(address(TOKEN))), uint32(uint160(JBConstants.NATIVE_TOKEN)), priceFeed);
109
- LOANS_CONTRACT = new REVLoans({
110
- controller: jbController(),
111
- suckerRegistry: IJBSuckerRegistry(address(new MockSuckerRegistry())),
112
- revId: FEE_PROJECT_ID,
113
- owner: address(this),
114
- permit2: permit2(),
115
- trustedForwarder: TRUSTED_FORWARDER
116
- });
117
- REV_OWNER = new REVOwner(
118
- IJBBuybackHookRegistry(address(MOCK_BUYBACK)),
119
- jbDirectory(),
120
- FEE_PROJECT_ID,
121
- SUCKER_REGISTRY,
122
- address(LOANS_CONTRACT),
123
- address(0)
124
- );
125
-
126
- REV_DEPLOYER = new REVDeployer{salt: REV_DEPLOYER_SALT}(
127
- jbController(),
128
- SUCKER_REGISTRY,
129
- FEE_PROJECT_ID,
130
- HOOK_DEPLOYER,
131
- PUBLISHER,
132
- IJBBuybackHookRegistry(address(MOCK_BUYBACK)),
133
- address(LOANS_CONTRACT),
134
- TRUSTED_FORWARDER,
135
- address(REV_OWNER)
136
- );
137
-
138
- REV_OWNER.setDeployer(REV_DEPLOYER);
139
-
140
- vm.prank(multisig());
141
- jbProjects().approve(address(REV_DEPLOYER), FEE_PROJECT_ID);
142
- _deployFeeProject();
143
- _deployRevnet();
144
- vm.deal(USER, 1000e18);
145
- }
146
-
147
- function _deployFeeProject() internal {
148
- JBAccountingContext[] memory acc = new JBAccountingContext[](2);
149
- acc[0] = JBAccountingContext({
150
- token: JBConstants.NATIVE_TOKEN, decimals: 18, currency: uint32(uint160(JBConstants.NATIVE_TOKEN))
151
- });
152
- acc[1] = JBAccountingContext({token: address(TOKEN), decimals: 6, currency: uint32(uint160(address(TOKEN)))});
153
- JBTerminalConfig[] memory tc = new JBTerminalConfig[](1);
154
- tc[0] = JBTerminalConfig({terminal: jbMultiTerminal(), accountingContextsToAccept: acc});
155
- REVStageConfig[] memory stages = new REVStageConfig[](1);
156
- JBSplit[] memory splits = new JBSplit[](1);
157
- splits[0].beneficiary = payable(multisig());
158
- splits[0].percent = 10_000;
159
- REVAutoIssuance[] memory ai = new REVAutoIssuance[](1);
160
- ai[0] = REVAutoIssuance({chainId: uint32(block.chainid), count: uint104(70_000e18), beneficiary: multisig()});
161
- stages[0] = REVStageConfig({
162
- startsAtOrAfter: uint40(block.timestamp),
163
- autoIssuances: ai,
164
- splitPercent: 2000,
165
- splits: splits,
166
- initialIssuance: uint112(1000e18),
167
- issuanceCutFrequency: 90 days,
168
- issuanceCutPercent: JBConstants.MAX_WEIGHT_CUT_PERCENT / 2,
169
- cashOutTaxRate: 6000,
170
- extraMetadata: 0
171
- });
172
- REVConfig memory cfg = REVConfig({
173
- // forge-lint: disable-next-line(named-struct-fields)
174
- description: REVDescription("Revnet", "$REV", "ipfs://test", "REV_TOKEN"),
175
- baseCurrency: uint32(uint160(JBConstants.NATIVE_TOKEN)),
176
- splitOperator: multisig(),
177
- stageConfigurations: stages
178
- });
179
- vm.prank(multisig());
180
- REV_DEPLOYER.deployFor({
181
- revnetId: FEE_PROJECT_ID,
182
- configuration: cfg,
183
- terminalConfigurations: tc,
184
- suckerDeploymentConfiguration: REVSuckerDeploymentConfig({
185
- deployerConfigurations: new JBSuckerDeployerConfig[](0), salt: keccak256("FEE")
186
- }),
187
- tiered721HookConfiguration: REVEmpty721Config.empty721Config(uint32(uint160(JBConstants.NATIVE_TOKEN))),
188
- allowedPosts: REVEmpty721Config.emptyAllowedPosts()
189
- });
190
- }
191
-
192
- function _deployRevnet() internal {
193
- JBAccountingContext[] memory acc = new JBAccountingContext[](2);
194
- acc[0] = JBAccountingContext({
195
- token: JBConstants.NATIVE_TOKEN, decimals: 18, currency: uint32(uint160(JBConstants.NATIVE_TOKEN))
196
- });
197
- acc[1] = JBAccountingContext({token: address(TOKEN), decimals: 6, currency: uint32(uint160(address(TOKEN)))});
198
- JBTerminalConfig[] memory tc = new JBTerminalConfig[](1);
199
- tc[0] = JBTerminalConfig({terminal: jbMultiTerminal(), accountingContextsToAccept: acc});
200
- REVStageConfig[] memory stages = new REVStageConfig[](1);
201
- JBSplit[] memory splits = new JBSplit[](1);
202
- splits[0].beneficiary = payable(multisig());
203
- splits[0].percent = 10_000;
204
- REVAutoIssuance[] memory ai = new REVAutoIssuance[](1);
205
- ai[0] = REVAutoIssuance({chainId: uint32(block.chainid), count: uint104(70_000e18), beneficiary: multisig()});
206
- stages[0] = REVStageConfig({
207
- startsAtOrAfter: uint40(block.timestamp),
208
- autoIssuances: ai,
209
- splitPercent: 2000,
210
- splits: splits,
211
- initialIssuance: uint112(1000e18),
212
- issuanceCutFrequency: 90 days,
213
- issuanceCutPercent: JBConstants.MAX_WEIGHT_CUT_PERCENT / 2,
214
- cashOutTaxRate: 6000,
215
- extraMetadata: 0
216
- });
217
- REVLoanSource[] memory ls = new REVLoanSource[](1);
218
- ls[0] = REVLoanSource({token: JBConstants.NATIVE_TOKEN, terminal: jbMultiTerminal()});
219
- REVConfig memory cfg = REVConfig({
220
- // forge-lint: disable-next-line(named-struct-fields)
221
- description: REVDescription("NANA", "$NANA", "ipfs://test2", "NANA_TOKEN"),
222
- baseCurrency: uint32(uint160(JBConstants.NATIVE_TOKEN)),
223
- splitOperator: multisig(),
224
- stageConfigurations: stages
225
- });
226
- (REVNET_ID,) = REV_DEPLOYER.deployFor({
227
- revnetId: 0,
228
- configuration: cfg,
229
- terminalConfigurations: tc,
230
- suckerDeploymentConfiguration: REVSuckerDeploymentConfig({
231
- deployerConfigurations: new JBSuckerDeployerConfig[](0), salt: keccak256("NANA")
232
- }),
233
- tiered721HookConfiguration: REVEmpty721Config.empty721Config(uint32(uint160(JBConstants.NATIVE_TOKEN))),
234
- allowedPosts: REVEmpty721Config.emptyAllowedPosts()
235
- });
236
- }
237
-
238
- function _setupLoan(
239
- address user,
240
- uint256 ethAmount,
241
- uint256 prepaidFee
242
- )
243
- internal
244
- returns (uint256 loanId, uint256 tokenCount, uint256 borrowAmount)
245
- {
246
- vm.prank(user);
247
- tokenCount =
248
- jbMultiTerminal().pay{value: ethAmount}(REVNET_ID, JBConstants.NATIVE_TOKEN, ethAmount, user, 0, "", "");
249
- borrowAmount =
250
- LOANS_CONTRACT.borrowableAmountFrom(REVNET_ID, tokenCount, 18, uint32(uint160(JBConstants.NATIVE_TOKEN)));
251
- if (borrowAmount == 0) return (0, tokenCount, 0);
252
- mockExpect(
253
- address(jbPermissions()),
254
- abi.encodeCall(IJBPermissions.hasPermission, (address(LOANS_CONTRACT), user, REVNET_ID, 11, true, true)),
255
- abi.encode(true)
256
- );
257
- REVLoanSource memory source = REVLoanSource({token: JBConstants.NATIVE_TOKEN, terminal: jbMultiTerminal()});
258
- vm.prank(user);
259
- (loanId,) = LOANS_CONTRACT.borrowFrom(REVNET_ID, source, 0, tokenCount, payable(user), prepaidFee, user);
260
- }
261
-
262
- /// @notice At exactly LOAN_LIQUIDATION_DURATION, determineSourceFeeAmount should revert with LoanExpired (>=
263
- /// boundary).
264
- function test_liquidationBoundary_exactDuration_isLiquidatable() public {
265
- (uint256 loanId,,) = _setupLoan(USER, 10e18, 25);
266
- require(loanId != 0, "Loan setup failed");
267
-
268
- REVLoan memory loan = LOANS_CONTRACT.loanOf(loanId);
269
-
270
- // Warp to one second past LOAN_LIQUIDATION_DURATION after creation.
271
- // The contract uses `>` (not `>=`) so the exact boundary is still repayable;
272
- // we need to exceed the boundary by 1 second to trigger the revert.
273
- vm.warp(loan.createdAt + LOANS_CONTRACT.LOAN_LIQUIDATION_DURATION() + 1);
274
-
275
- // timeSinceLoanCreated > LOAN_LIQUIDATION_DURATION → revert
276
- vm.expectRevert(
277
- abi.encodeWithSelector(
278
- REVLoans.REVLoans_LoanExpired.selector,
279
- LOANS_CONTRACT.LOAN_LIQUIDATION_DURATION() + 1,
280
- LOANS_CONTRACT.LOAN_LIQUIDATION_DURATION()
281
- )
282
- );
283
- LOANS_CONTRACT.determineSourceFeeAmount(loan, loan.amount);
284
- }
285
-
286
- /// @notice At LOAN_LIQUIDATION_DURATION - 1, the loan should still be manageable (not expired).
287
- function test_liquidationBoundary_oneBefore_notLiquidatable() public {
288
- (uint256 loanId,,) = _setupLoan(USER, 10e18, 25);
289
- require(loanId != 0, "Loan setup failed");
290
-
291
- REVLoan memory loan = LOANS_CONTRACT.loanOf(loanId);
292
-
293
- // Warp to one second before the liquidation boundary
294
- vm.warp(loan.createdAt + LOANS_CONTRACT.LOAN_LIQUIDATION_DURATION() - 1);
295
-
296
- // This should NOT revert — the loan is still within the liquidation window
297
- uint256 fee = LOANS_CONTRACT.determineSourceFeeAmount(loan, loan.amount);
298
-
299
- // Fee should be > 0 since we're past the prepaid duration but before liquidation
300
- assertTrue(fee > 0, "Fee should be nonzero for a loan past its prepaid period");
301
- }
302
-
303
- /// @notice Sending ETH to the non-payable reallocateCollateralFromLoan should revert.
304
- /// @dev Since the function is not payable, Solidity prevents sending ETH at compile time.
305
- /// We use a low-level call to bypass this and verify the EVM-level revert.
306
- function test_reallocate_withETHValue_reverts() public {
307
- (uint256 loanId, uint256 tokenCount,) = _setupLoan(USER, 10e18, 25);
308
- require(loanId != 0, "Loan setup failed");
309
-
310
- // Encode the function call
311
- bytes memory callData = abi.encodeWithSelector(
312
- LOANS_CONTRACT.reallocateCollateralFromLoan.selector,
313
- loanId,
314
- tokenCount / 10,
315
- REVLoanSource({token: JBConstants.NATIVE_TOKEN, terminal: jbMultiTerminal()}),
316
- 0,
317
- 0,
318
- USER,
319
- 25
320
- );
321
-
322
- // Low-level call with msg.value to bypass Solidity's payable check
323
- vm.prank(USER);
324
- (bool success,) = address(LOANS_CONTRACT).call{value: 1 ether}(callData);
325
- assertFalse(success, "Sending ETH to non-payable reallocate should revert");
326
- }
327
-
328
- /// @notice Calling reallocateCollateralFromLoan without ETH should work (given valid params).
329
- function test_reallocate_withoutETHValue_succeeds() public {
330
- (uint256 loanId, uint256 tokenCount,) = _setupLoan(USER, 10e18, 25);
331
- require(loanId != 0, "Loan setup failed");
332
-
333
- // Inflate surplus so collateral removal is viable
334
- address donor = makeAddr("donor");
335
- vm.deal(donor, 500e18);
336
- vm.prank(donor);
337
- jbMultiTerminal().addToBalanceOf{value: 500e18}(REVNET_ID, JBConstants.NATIVE_TOKEN, 500e18, false, "", "");
338
-
339
- // Get extra tokens to add as collateral to the new loan
340
- vm.prank(USER);
341
- uint256 extraTokens =
342
- jbMultiTerminal().pay{value: 50e18}(REVNET_ID, JBConstants.NATIVE_TOKEN, 50e18, USER, 0, "", "");
343
-
344
- uint256 collateralToTransfer = tokenCount / 10;
345
-
346
- REVLoanSource memory source = REVLoanSource({token: JBConstants.NATIVE_TOKEN, terminal: jbMultiTerminal()});
347
-
348
- // Mock burn permission
349
- mockExpect(
350
- address(jbPermissions()),
351
- abi.encodeCall(IJBPermissions.hasPermission, (address(LOANS_CONTRACT), USER, REVNET_ID, 11, true, true)),
352
- abi.encode(true)
353
- );
354
-
355
- // Call without msg.value — should succeed
356
- vm.prank(USER);
357
- (uint256 reallocatedLoanId, uint256 newLoanId,,) = LOANS_CONTRACT.reallocateCollateralFromLoan(
358
- loanId, collateralToTransfer, source, 0, extraTokens, payable(USER), 25
359
- );
360
-
361
- assertTrue(reallocatedLoanId != 0, "Reallocated loan should exist");
362
- assertTrue(newLoanId != 0, "New loan should exist");
363
- }
364
-
365
- // ==================== Mixed-Decimal Normalization Tests ====================
366
-
367
- // forge-lint: disable-next-line(mixed-case-variable)
368
- uint256 MIXED_REVNET_ID;
369
-
370
- /// @notice Deploy a revnet with BOTH ETH (18 dec) and TOKEN (6 dec) as loan sources.
371
- function _deployMixedDecimalRevnet() internal {
372
- JBAccountingContext[] memory acc = new JBAccountingContext[](2);
373
- acc[0] = JBAccountingContext({
374
- token: JBConstants.NATIVE_TOKEN, decimals: 18, currency: uint32(uint160(JBConstants.NATIVE_TOKEN))
375
- });
376
- acc[1] = JBAccountingContext({token: address(TOKEN), decimals: 6, currency: uint32(uint160(address(TOKEN)))});
377
- JBTerminalConfig[] memory tc = new JBTerminalConfig[](1);
378
- tc[0] = JBTerminalConfig({terminal: jbMultiTerminal(), accountingContextsToAccept: acc});
379
- REVStageConfig[] memory stages = new REVStageConfig[](1);
380
- JBSplit[] memory splits = new JBSplit[](1);
381
- splits[0].beneficiary = payable(multisig());
382
- splits[0].percent = 10_000;
383
- REVAutoIssuance[] memory ai = new REVAutoIssuance[](1);
384
- ai[0] = REVAutoIssuance({chainId: uint32(block.chainid), count: uint104(70_000e18), beneficiary: multisig()});
385
- // cashOutTaxRate=0 for proportional math (simpler assertions).
386
- stages[0] = REVStageConfig({
387
- startsAtOrAfter: uint40(block.timestamp),
388
- autoIssuances: ai,
389
- splitPercent: 2000,
390
- splits: splits,
391
- initialIssuance: uint112(1000e18),
392
- issuanceCutFrequency: 90 days,
393
- issuanceCutPercent: JBConstants.MAX_WEIGHT_CUT_PERCENT / 2,
394
- cashOutTaxRate: 0,
395
- extraMetadata: 0
396
- });
397
- REVLoanSource[] memory ls = new REVLoanSource[](2);
398
- ls[0] = REVLoanSource({token: JBConstants.NATIVE_TOKEN, terminal: jbMultiTerminal()});
399
- ls[1] = REVLoanSource({token: address(TOKEN), terminal: jbMultiTerminal()});
400
- REVConfig memory cfg = REVConfig({
401
- // forge-lint: disable-next-line(named-struct-fields)
402
- description: REVDescription("Mixed", "$MIX", "ipfs://mix", "MIX_TOKEN"),
403
- baseCurrency: uint32(uint160(JBConstants.NATIVE_TOKEN)),
404
- splitOperator: multisig(),
405
- stageConfigurations: stages
406
- });
407
- (MIXED_REVNET_ID,) = REV_DEPLOYER.deployFor({
408
- revnetId: 0,
409
- configuration: cfg,
410
- terminalConfigurations: tc,
411
- suckerDeploymentConfiguration: REVSuckerDeploymentConfig({
412
- deployerConfigurations: new JBSuckerDeployerConfig[](0), salt: keccak256("MIXED")
413
- }),
414
- tiered721HookConfiguration: REVEmpty721Config.empty721Config(uint32(uint160(JBConstants.NATIVE_TOKEN))),
415
- allowedPosts: REVEmpty721Config.emptyAllowedPosts()
416
- });
417
- }
418
-
419
- /// @notice When only the ETH source has borrows, TOKEN source (0 borrowed) should be skipped via `continue`.
420
- /// @dev Exercises the `if (tokensLoaned == 0) continue` path in _totalBorrowedFrom.
421
- function test_mixedDecimals_zeroBorrowFromTokenSource_continuePath() public {
422
- _deployMixedDecimalRevnet();
423
-
424
- // Pay ETH to get project tokens.
425
- vm.prank(USER);
426
- uint256 tokenCount =
427
- jbMultiTerminal().pay{value: 10e18}(MIXED_REVNET_ID, JBConstants.NATIVE_TOKEN, 10e18, USER, 0, "", "");
428
-
429
- // Borrow from ETH source.
430
- uint256 borrowable = LOANS_CONTRACT.borrowableAmountFrom(
431
- MIXED_REVNET_ID, tokenCount, 18, uint32(uint160(JBConstants.NATIVE_TOKEN))
432
- );
433
- require(borrowable > 0, "Must have borrowable amount");
434
-
435
- mockExpect(
436
- address(jbPermissions()),
437
- abi.encodeCall(
438
- IJBPermissions.hasPermission, (address(LOANS_CONTRACT), USER, MIXED_REVNET_ID, 11, true, true)
439
- ),
440
- abi.encode(true)
441
- );
442
- REVLoanSource memory ethSource = REVLoanSource({token: JBConstants.NATIVE_TOKEN, terminal: jbMultiTerminal()});
443
- vm.prank(USER);
444
- (uint256 loanId, REVLoan memory loan) =
445
- LOANS_CONTRACT.borrowFrom(MIXED_REVNET_ID, ethSource, 0, tokenCount, payable(USER), 25, USER);
446
-
447
- // Verify loan created and TOKEN source has zero borrowed.
448
- assertTrue(loanId != 0, "ETH loan should be created");
449
- assertTrue(loan.amount > 0, "Loan amount should be nonzero");
450
- assertEq(
451
- LOANS_CONTRACT.totalBorrowedFrom(MIXED_REVNET_ID, jbMultiTerminal(), address(TOKEN)),
452
- 0,
453
- "TOKEN source should have zero borrowed"
454
- );
455
- assertTrue(
456
- LOANS_CONTRACT.totalBorrowedFrom(MIXED_REVNET_ID, jbMultiTerminal(), JBConstants.NATIVE_TOKEN) > 0,
457
- "ETH source should have nonzero borrowed"
458
- );
459
- }
460
-
461
- /// @notice Borrow from TOKEN (6-decimal) source, verify totalBorrowed tracked and borrowable works in 18-dec
462
- /// context. @dev This is the core normalization test. Without decimal normalization, _totalBorrowedFrom would treat
463
- /// the 6-decimal TOKEN amount as if it were in 18 decimals, making it ~10^12 times too small.
464
- function test_mixedDecimals_borrowFromTokenSource_normalizedCorrectly() public {
465
- _deployMixedDecimalRevnet();
466
-
467
- // Pay with TOKEN to get project tokens AND create TOKEN surplus in the terminal.
468
- // Using TOKEN (not ETH) ensures the borrowable amount from TOKEN source stays within
469
- // the terminal's actual TOKEN balance.
470
- deal(address(TOKEN), USER, 2_000_000e6);
471
- vm.prank(USER);
472
- TOKEN.approve(address(jbMultiTerminal()), type(uint256).max);
473
- vm.prank(USER);
474
- uint256 tokenCount = jbMultiTerminal().pay(MIXED_REVNET_ID, address(TOKEN), 1_000_000e6, USER, 0, "", "");
475
- require(tokenCount > 0, "Must receive project tokens");
476
-
477
- // Record borrowable BEFORE any borrow (queried in 18-decimal ETH context).
478
- uint256 smallCollateral = tokenCount / 10;
479
- uint256 borrowableBefore = LOANS_CONTRACT.borrowableAmountFrom(
480
- MIXED_REVNET_ID, smallCollateral, 18, uint32(uint160(JBConstants.NATIVE_TOKEN))
481
- );
482
- assertTrue(borrowableBefore > 0, "Must have borrowable amount before borrow");
483
-
484
- // Borrow from TOKEN source using a small portion of collateral.
485
- mockExpect(
486
- address(jbPermissions()),
487
- abi.encodeCall(
488
- IJBPermissions.hasPermission, (address(LOANS_CONTRACT), USER, MIXED_REVNET_ID, 11, true, true)
489
- ),
490
- abi.encode(true)
491
- );
492
- REVLoanSource memory tokenSource = REVLoanSource({token: address(TOKEN), terminal: jbMultiTerminal()});
493
- vm.prank(USER);
494
- (uint256 loanId, REVLoan memory loan) =
495
- LOANS_CONTRACT.borrowFrom(MIXED_REVNET_ID, tokenSource, 0, smallCollateral, payable(USER), 25, USER);
496
-
497
- assertTrue(loanId != 0, "TOKEN loan should be created");
498
- assertTrue(loan.amount > 0, "Loan amount should be nonzero");
499
-
500
- // Verify totalBorrowedFrom tracks the raw 6-decimal amount.
501
- uint256 tokenBorrowed = LOANS_CONTRACT.totalBorrowedFrom(MIXED_REVNET_ID, jbMultiTerminal(), address(TOKEN));
502
- assertEq(tokenBorrowed, loan.amount, "totalBorrowedFrom should match loan amount in source decimals");
503
-
504
- // Query borrowable for more collateral in 18-decimal ETH context.
505
- // This calls _totalBorrowedFrom which must normalize the 6-dec TOKEN amount to 18-dec.
506
- // Without normalization: TOKEN borrow treated as near-zero → borrowable barely changes.
507
- // With normalization: TOKEN borrow properly scaled → borrowable reflects the outstanding debt.
508
- uint256 borrowableAfter = LOANS_CONTRACT.borrowableAmountFrom(
509
- MIXED_REVNET_ID, smallCollateral, 18, uint32(uint160(JBConstants.NATIVE_TOKEN))
510
- );
511
-
512
- // borrowableAfter should still be nonzero (the revnet has surplus).
513
- assertTrue(borrowableAfter > 0, "Should still have borrowable amount after TOKEN borrow");
514
-
515
- // Also query in TOKEN's own 6-decimal context to verify the same-currency normalization path.
516
- // Since only TOKEN source has borrows and ETH source has 0 (skipped via `continue`), this is safe.
517
- uint256 borrowableInToken =
518
- LOANS_CONTRACT.borrowableAmountFrom(MIXED_REVNET_ID, smallCollateral, 6, uint32(uint160(address(TOKEN))));
519
- assertTrue(borrowableInToken > 0, "Borrowable in TOKEN terms should be nonzero");
520
- }
521
-
522
- /// @notice Borrow from both ETH and TOKEN sources, verify both borrows are tracked and aggregated.
523
- /// @dev TOKEN borrow MUST happen first: when borrowing from TOKEN source, _totalBorrowedFrom is queried
524
- /// in 6-dec TOKEN context. If ETH had borrows, converting ETH→TOKEN at 6 decimals causes the inverse
525
- /// price feed to truncate to 0 (mulDiv(1e6,1e6,1e21)=0). Borrowing TOKEN first ensures ETH=0→continue.
526
- /// The subsequent ETH borrow then exercises cross-decimal normalization (TOKEN 6-dec → ETH 18-dec) using
527
- /// the DIRECT TOKEN→ETH feed which works at 18 decimals.
528
- function test_mixedDecimals_borrowFromBothSources_aggregatesCorrectly() public {
529
- _deployMixedDecimalRevnet();
530
-
531
- // STEP 1: Pay TOKEN ONLY to get project tokens and create TOKEN-only surplus.
532
- // This avoids ETH surplus inflating the TOKEN borrowable beyond the terminal's TOKEN balance.
533
- deal(address(TOKEN), USER, 10_000_000e6);
534
- vm.prank(USER);
535
- TOKEN.approve(address(jbMultiTerminal()), type(uint256).max);
536
- vm.prank(USER);
537
- uint256 tokenTokenCount = jbMultiTerminal().pay(MIXED_REVNET_ID, address(TOKEN), 5_000_000e6, USER, 0, "", "");
538
-
539
- // STEP 2: Borrow from TOKEN source (ETH totalBorrowed=0 → skipped via `continue`, no inverse price needed).
540
- uint256 smallCollateral = tokenTokenCount / 20;
541
- mockExpect(
542
- address(jbPermissions()),
543
- abi.encodeCall(
544
- IJBPermissions.hasPermission, (address(LOANS_CONTRACT), USER, MIXED_REVNET_ID, 11, true, true)
545
- ),
546
- abi.encode(true)
547
- );
548
- REVLoanSource memory tokenSource = REVLoanSource({token: address(TOKEN), terminal: jbMultiTerminal()});
549
- vm.prank(USER);
550
- (uint256 tokenLoanId,) =
551
- LOANS_CONTRACT.borrowFrom(MIXED_REVNET_ID, tokenSource, 0, smallCollateral, payable(USER), 25, USER);
552
- assertTrue(tokenLoanId != 0, "TOKEN loan should be created");
553
-
554
- // STEP 3: Pay ETH to create ETH surplus.
555
- vm.prank(USER);
556
- uint256 ethTokenCount =
557
- jbMultiTerminal().pay{value: 10e18}(MIXED_REVNET_ID, JBConstants.NATIVE_TOKEN, 10e18, USER, 0, "", "");
558
-
559
- // STEP 4: Borrow from ETH source. Now _totalBorrowedFrom(revnetId, 18, ETH_CURRENCY) must normalize
560
- // the TOKEN borrow (6 dec) to 18 dec using the DIRECT TOKEN→ETH feed. This is the key normalization test.
561
- uint256 ethCollateral = ethTokenCount / 20;
562
- mockExpect(
563
- address(jbPermissions()),
564
- abi.encodeCall(
565
- IJBPermissions.hasPermission, (address(LOANS_CONTRACT), USER, MIXED_REVNET_ID, 11, true, true)
566
- ),
567
- abi.encode(true)
568
- );
569
- REVLoanSource memory ethSource = REVLoanSource({token: JBConstants.NATIVE_TOKEN, terminal: jbMultiTerminal()});
570
- vm.prank(USER);
571
- (uint256 ethLoanId,) =
572
- LOANS_CONTRACT.borrowFrom(MIXED_REVNET_ID, ethSource, 0, ethCollateral, payable(USER), 25, USER);
573
- assertTrue(ethLoanId != 0, "ETH loan should be created");
574
-
575
- // Both sources should have tracked borrows.
576
- uint256 ethBorrowed =
577
- LOANS_CONTRACT.totalBorrowedFrom(MIXED_REVNET_ID, jbMultiTerminal(), JBConstants.NATIVE_TOKEN);
578
- uint256 tokenBorrowed = LOANS_CONTRACT.totalBorrowedFrom(MIXED_REVNET_ID, jbMultiTerminal(), address(TOKEN));
579
- assertTrue(ethBorrowed > 0, "ETH borrow should be tracked");
580
- assertTrue(tokenBorrowed > 0, "TOKEN borrow should be tracked");
581
-
582
- // The total number of loans should be 2.
583
- assertEq(LOANS_CONTRACT.totalLoansBorrowedFor(MIXED_REVNET_ID), 2, "Should have 2 loans");
584
-
585
- // Query borrowable in 18-decimal ETH context. This exercises _totalBorrowedFrom's
586
- // cross-decimal normalization: TOKEN borrows (6 dec) must be normalized to 18 dec before
587
- // aggregation with the direct TOKEN→ETH price feed.
588
- uint256 borrowableInEth = LOANS_CONTRACT.borrowableAmountFrom(
589
- MIXED_REVNET_ID, ethCollateral, 18, uint32(uint160(JBConstants.NATIVE_TOKEN))
590
- );
591
- assertTrue(borrowableInEth > 0, "Should still have borrowable after both borrows (18-dec ETH)");
592
- }
593
- }