@rev-net/core-v6 0.0.37 → 0.0.39

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 (107) 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 +60 -65
  9. package/src/REVHiddenTokens.sol +2 -2
  10. package/src/REVLoans.sol +17 -10
  11. package/src/REVOwner.sol +121 -14
  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/ADMINISTRATION.md +0 -73
  16. package/ARCHITECTURE.md +0 -116
  17. package/AUDIT_INSTRUCTIONS.md +0 -90
  18. package/RISKS.md +0 -107
  19. package/SKILLS.md +0 -46
  20. package/STYLE_GUIDE.md +0 -610
  21. package/USER_JOURNEYS.md +0 -195
  22. package/foundry.lock +0 -11
  23. package/slither-ci.config.json +0 -10
  24. package/sphinx.lock +0 -507
  25. package/test/REV.integrations.t.sol +0 -573
  26. package/test/REVAutoIssuanceFuzz.t.sol +0 -328
  27. package/test/REVDeployerRegressions.t.sol +0 -396
  28. package/test/REVInvincibility.t.sol +0 -1371
  29. package/test/REVInvincibilityHandler.sol +0 -387
  30. package/test/REVLifecycle.t.sol +0 -420
  31. package/test/REVLoans.invariants.t.sol +0 -724
  32. package/test/REVLoansAttacks.t.sol +0 -816
  33. package/test/REVLoansFeeRecovery.t.sol +0 -783
  34. package/test/REVLoansFindings.t.sol +0 -711
  35. package/test/REVLoansRegressions.t.sol +0 -364
  36. package/test/REVLoansSourceFeeRecovery.t.sol +0 -517
  37. package/test/REVLoansSourced.t.sol +0 -1839
  38. package/test/REVLoansUnSourced.t.sol +0 -409
  39. package/test/TestAuditFixVerification.t.sol +0 -675
  40. package/test/TestBurnHeldTokens.t.sol +0 -394
  41. package/test/TestCEIPattern.t.sol +0 -508
  42. package/test/TestCashOutCallerValidation.t.sol +0 -452
  43. package/test/TestConversionDocumentation.t.sol +0 -365
  44. package/test/TestCrossCurrencyReclaim.t.sol +0 -610
  45. package/test/TestCrossSourceReallocation.t.sol +0 -361
  46. package/test/TestERC2771MetaTx.t.sol +0 -585
  47. package/test/TestEmptyBuybackSpecs.t.sol +0 -300
  48. package/test/TestFlashLoanSurplus.t.sol +0 -365
  49. package/test/TestHiddenTokens.t.sol +0 -474
  50. package/test/TestHookArrayOOB.t.sol +0 -278
  51. package/test/TestLiquidationBehavior.t.sol +0 -398
  52. package/test/TestLoanSourceRotation.t.sol +0 -553
  53. package/test/TestLoansCashOutDelay.t.sol +0 -493
  54. package/test/TestLongTailEconomics.t.sol +0 -677
  55. package/test/TestLowFindings.t.sol +0 -677
  56. package/test/TestMixedFixes.t.sol +0 -593
  57. package/test/TestPermit2Signatures.t.sol +0 -683
  58. package/test/TestReallocationSandwich.t.sol +0 -412
  59. package/test/TestRevnetRegressions.t.sol +0 -350
  60. package/test/TestSplitWeightAdjustment.t.sol +0 -527
  61. package/test/TestSplitWeightE2E.t.sol +0 -605
  62. package/test/TestSplitWeightFork.t.sol +0 -855
  63. package/test/TestStageTransitionBorrowable.t.sol +0 -301
  64. package/test/TestSwapTerminalPermission.t.sol +0 -262
  65. package/test/TestTerminalEncodingInHash.t.sol +0 -326
  66. package/test/TestUint112Overflow.t.sol +0 -311
  67. package/test/TestZeroAmountLoanGuard.t.sol +0 -378
  68. package/test/TestZeroRepayment.t.sol +0 -354
  69. package/test/audit/CrossChainBuybackRouteMismatch.t.sol +0 -184
  70. package/test/audit/HiddenSupplyCashout.t.sol +0 -61
  71. package/test/audit/LoanIdOverflowGuard.t.sol +0 -523
  72. package/test/audit/NemesisVerification.t.sol +0 -97
  73. package/test/audit/OperatorDelegation.t.sol +0 -356
  74. package/test/audit/PhantomSurplusTerminal.t.sol +0 -367
  75. package/test/audit/REVOwnerCurrencyMismatch.t.sol +0 -188
  76. package/test/audit/REVOwnerRemoteSurplusCurrencyMismatch.t.sol +0 -140
  77. package/test/audit/ReallocatePermission.t.sol +0 -363
  78. package/test/audit/RemoteLoanAccountingGap.t.sol +0 -74
  79. package/test/audit/SupportsInterfaceTest.t.sol +0 -51
  80. package/test/audit/TestFeeAllowanceLeak.t.sol +0 -197
  81. package/test/audit/TestLoansAndDeployerFixes.t.sol +0 -576
  82. package/test/fork/ForkTestBase.sol +0 -727
  83. package/test/fork/TestAutoIssuanceFork.t.sol +0 -148
  84. package/test/fork/TestCashOutFork.t.sol +0 -253
  85. package/test/fork/TestIssuanceDecayFork.t.sol +0 -158
  86. package/test/fork/TestLoanAdversarialFork.t.sol +0 -744
  87. package/test/fork/TestLoanBorrowFork.t.sol +0 -163
  88. package/test/fork/TestLoanCrossRulesetFork.t.sol +0 -308
  89. package/test/fork/TestLoanERC20Fork.t.sol +0 -459
  90. package/test/fork/TestLoanLiquidationFork.t.sol +0 -135
  91. package/test/fork/TestLoanReallocateFork.t.sol +0 -113
  92. package/test/fork/TestLoanRepayFork.t.sol +0 -188
  93. package/test/fork/TestLoanTransferFork.t.sol +0 -143
  94. package/test/fork/TestPermit2PaymentFork.t.sol +0 -300
  95. package/test/fork/TestSplitWeightFork.t.sol +0 -189
  96. package/test/helpers/MaliciousContracts.sol +0 -247
  97. package/test/helpers/REVEmpty721Config.sol +0 -45
  98. package/test/mock/MockBuybackCashOutRecorder.sol +0 -84
  99. package/test/mock/MockBuybackDataHook.sol +0 -112
  100. package/test/mock/MockBuybackDataHookMintPath.sol +0 -68
  101. package/test/mock/MockSuckerRegistry.sol +0 -17
  102. package/test/regression/TestBurnPermissionRequired.t.sol +0 -294
  103. package/test/regression/TestCashOutBuybackFeeLeak.t.sol +0 -232
  104. package/test/regression/TestCrossRevnetLiquidation.t.sol +0 -255
  105. package/test/regression/TestCumulativeLoanCounter.t.sol +0 -361
  106. package/test/regression/TestLiquidateGapHandling.t.sol +0 -394
  107. package/test/regression/TestZeroPriceFeed.t.sol +0 -422
@@ -1,517 +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
- // forge-lint: disable-next-line(unaliased-plain-import)
9
- import /* {*} from */ "./../src/REVDeployer.sol";
10
- // forge-lint: disable-next-line(unaliased-plain-import)
11
- import "@croptop/core-v6/src/CTPublisher.sol";
12
- import {MockBuybackDataHook} from "./mock/MockBuybackDataHook.sol";
13
-
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
-
25
- import {JBConstants} from "@bananapus/core-v6/src/libraries/JBConstants.sol";
26
- import {JBAccountingContext} from "@bananapus/core-v6/src/structs/JBAccountingContext.sol";
27
- import {REVLoans} from "../src/REVLoans.sol";
28
- import {REVLoan} from "../src/structs/REVLoan.sol";
29
- import {REVStageConfig, REVAutoIssuance} from "../src/structs/REVStageConfig.sol";
30
- import {REVLoanSource} from "../src/structs/REVLoanSource.sol";
31
- import {REVDescription} from "../src/structs/REVDescription.sol";
32
- import {IREVLoans} from "./../src/interfaces/IREVLoans.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
- struct SourceFeeProjectConfig {
48
- REVConfig configuration;
49
- JBTerminalConfig[] terminalConfigurations;
50
- REVSuckerDeploymentConfig suckerDeploymentConfiguration;
51
- }
52
-
53
- /// @title REVLoansSourceFeeRecovery
54
- /// @notice Tests for the source fee try-catch in REVLoans._adjust().
55
- /// @dev When loan.source.terminal.pay() reverts during source fee payment, the borrower
56
- /// should receive the source fee amount back instead of losing it.
57
- contract REVLoansSourceFeeRecovery is TestBaseWorkflow {
58
- // forge-lint: disable-next-line(mixed-case-variable)
59
- bytes32 REV_DEPLOYER_SALT = "REVDeployer";
60
- // forge-lint: disable-next-line(mixed-case-variable)
61
- bytes32 ERC20_SALT = "REV_TOKEN";
62
-
63
- // forge-lint: disable-next-line(mixed-case-variable)
64
- REVDeployer REV_DEPLOYER;
65
- // forge-lint: disable-next-line(mixed-case-variable)
66
- REVOwner REV_OWNER;
67
- // forge-lint: disable-next-line(mixed-case-variable)
68
- JB721TiersHook EXAMPLE_HOOK;
69
- // forge-lint: disable-next-line(mixed-case-variable)
70
- IJB721TiersHookDeployer HOOK_DEPLOYER;
71
- // forge-lint: disable-next-line(mixed-case-variable)
72
- IJB721TiersHookStore HOOK_STORE;
73
- // forge-lint: disable-next-line(mixed-case-variable)
74
- IJBAddressRegistry ADDRESS_REGISTRY;
75
- // forge-lint: disable-next-line(mixed-case-variable)
76
- IREVLoans LOANS_CONTRACT;
77
- // forge-lint: disable-next-line(mixed-case-variable)
78
- IJBSuckerRegistry SUCKER_REGISTRY;
79
- // forge-lint: disable-next-line(mixed-case-variable)
80
- CTPublisher PUBLISHER;
81
- // forge-lint: disable-next-line(mixed-case-variable)
82
- MockBuybackDataHook MOCK_BUYBACK;
83
-
84
- // forge-lint: disable-next-line(mixed-case-variable)
85
- uint256 FEE_PROJECT_ID;
86
- // forge-lint: disable-next-line(mixed-case-variable)
87
- uint256 REVNET_ID;
88
-
89
- // forge-lint: disable-next-line(mixed-case-variable)
90
- address USER = makeAddr("user");
91
- address private constant TRUSTED_FORWARDER = 0xB2b5841DBeF766d4b521221732F9B618fCf34A87;
92
-
93
- function _getFeeProjectConfig() internal view returns (SourceFeeProjectConfig memory) {
94
- uint8 decimals = 18;
95
- uint256 decimalMultiplier = 10 ** decimals;
96
-
97
- JBAccountingContext[] memory accountingContextsToAccept = new JBAccountingContext[](1);
98
- accountingContextsToAccept[0] = JBAccountingContext({
99
- token: JBConstants.NATIVE_TOKEN, decimals: 18, currency: uint32(uint160(JBConstants.NATIVE_TOKEN))
100
- });
101
-
102
- JBTerminalConfig[] memory terminalConfigurations = new JBTerminalConfig[](1);
103
- terminalConfigurations[0] =
104
- JBTerminalConfig({terminal: jbMultiTerminal(), accountingContextsToAccept: accountingContextsToAccept});
105
-
106
- REVStageConfig[] memory stageConfigurations = new REVStageConfig[](1);
107
- JBSplit[] memory splits = new JBSplit[](1);
108
- splits[0].beneficiary = payable(multisig());
109
- splits[0].percent = 10_000;
110
-
111
- REVAutoIssuance[] memory issuanceConfs = new REVAutoIssuance[](1);
112
- issuanceConfs[0] = REVAutoIssuance({
113
- // forge-lint: disable-next-line(unsafe-typecast)
114
- chainId: uint32(block.chainid),
115
- // forge-lint: disable-next-line(unsafe-typecast)
116
- count: uint104(70_000 * decimalMultiplier),
117
- beneficiary: multisig()
118
- });
119
-
120
- stageConfigurations[0] = REVStageConfig({
121
- startsAtOrAfter: uint40(block.timestamp),
122
- autoIssuances: issuanceConfs,
123
- splitPercent: 2000,
124
- splits: splits,
125
- // forge-lint: disable-next-line(unsafe-typecast)
126
- initialIssuance: uint112(1000 * decimalMultiplier),
127
- issuanceCutFrequency: 90 days,
128
- issuanceCutPercent: JBConstants.MAX_WEIGHT_CUT_PERCENT / 2,
129
- cashOutTaxRate: 6000,
130
- extraMetadata: 0
131
- });
132
-
133
- REVConfig memory revnetConfiguration = REVConfig({
134
- description: REVDescription({
135
- name: "Revnet",
136
- ticker: "$REV",
137
- uri: "ipfs://QmNRHT91HcDgMcenebYX7rJigt77cgNcosvuhX21wkF3tx",
138
- salt: ERC20_SALT
139
- }),
140
- baseCurrency: uint32(uint160(JBConstants.NATIVE_TOKEN)),
141
- splitOperator: multisig(),
142
- stageConfigurations: stageConfigurations
143
- });
144
-
145
- return SourceFeeProjectConfig({
146
- configuration: revnetConfiguration,
147
- terminalConfigurations: terminalConfigurations,
148
- suckerDeploymentConfiguration: REVSuckerDeploymentConfig({
149
- deployerConfigurations: new JBSuckerDeployerConfig[](0), salt: keccak256(abi.encodePacked("REV"))
150
- })
151
- });
152
- }
153
-
154
- function _getRevnetConfig() internal view returns (SourceFeeProjectConfig memory) {
155
- uint8 decimals = 18;
156
- uint256 decimalMultiplier = 10 ** decimals;
157
-
158
- JBAccountingContext[] memory accountingContextsToAccept = new JBAccountingContext[](1);
159
- accountingContextsToAccept[0] = JBAccountingContext({
160
- token: JBConstants.NATIVE_TOKEN, decimals: 18, currency: uint32(uint160(JBConstants.NATIVE_TOKEN))
161
- });
162
-
163
- JBTerminalConfig[] memory terminalConfigurations = new JBTerminalConfig[](1);
164
- terminalConfigurations[0] =
165
- JBTerminalConfig({terminal: jbMultiTerminal(), accountingContextsToAccept: accountingContextsToAccept});
166
-
167
- JBSplit[] memory splits = new JBSplit[](1);
168
- splits[0].beneficiary = payable(multisig());
169
- splits[0].percent = 10_000;
170
-
171
- REVStageConfig[] memory stageConfigurations = new REVStageConfig[](1);
172
- REVAutoIssuance[] memory issuanceConfs = new REVAutoIssuance[](1);
173
- issuanceConfs[0] = REVAutoIssuance({
174
- // forge-lint: disable-next-line(unsafe-typecast)
175
- chainId: uint32(block.chainid),
176
- // forge-lint: disable-next-line(unsafe-typecast)
177
- count: uint104(70_000 * decimalMultiplier),
178
- beneficiary: multisig()
179
- });
180
-
181
- stageConfigurations[0] = REVStageConfig({
182
- startsAtOrAfter: uint40(block.timestamp),
183
- autoIssuances: issuanceConfs,
184
- splitPercent: 2000,
185
- splits: splits,
186
- // forge-lint: disable-next-line(unsafe-typecast)
187
- initialIssuance: uint112(1000 * decimalMultiplier),
188
- issuanceCutFrequency: 90 days,
189
- issuanceCutPercent: JBConstants.MAX_WEIGHT_CUT_PERCENT / 2,
190
- cashOutTaxRate: 6000,
191
- extraMetadata: 0
192
- });
193
-
194
- REVLoanSource[] memory _loanSources = new REVLoanSource[](1);
195
- _loanSources[0] = REVLoanSource({token: JBConstants.NATIVE_TOKEN, terminal: jbMultiTerminal()});
196
-
197
- REVConfig memory revnetConfiguration = REVConfig({
198
- description: REVDescription({
199
- name: "NANA",
200
- ticker: "$NANA",
201
- uri: "ipfs://QmNRHT91HcDgMcenebYX7rJigt77cgNxosvuhX21wkF3tx",
202
- salt: "NANA_TOKEN"
203
- }),
204
- baseCurrency: uint32(uint160(JBConstants.NATIVE_TOKEN)),
205
- splitOperator: multisig(),
206
- stageConfigurations: stageConfigurations
207
- });
208
-
209
- return SourceFeeProjectConfig({
210
- configuration: revnetConfiguration,
211
- terminalConfigurations: terminalConfigurations,
212
- suckerDeploymentConfiguration: REVSuckerDeploymentConfig({
213
- deployerConfigurations: new JBSuckerDeployerConfig[](0), salt: keccak256(abi.encodePacked("NANA"))
214
- })
215
- });
216
- }
217
-
218
- function setUp() public override {
219
- super.setUp();
220
-
221
- FEE_PROJECT_ID = jbProjects().createFor(multisig());
222
-
223
- SUCKER_REGISTRY = new JBSuckerRegistry(jbDirectory(), jbPermissions(), multisig(), address(0));
224
- HOOK_STORE = new JB721TiersHookStore();
225
- EXAMPLE_HOOK = new JB721TiersHook(
226
- jbDirectory(),
227
- jbPermissions(),
228
- jbPrices(),
229
- jbRulesets(),
230
- HOOK_STORE,
231
- jbSplits(),
232
- IJB721CheckpointsDeployer(address(new JB721CheckpointsDeployer())),
233
- multisig()
234
- );
235
- ADDRESS_REGISTRY = new JBAddressRegistry();
236
- HOOK_DEPLOYER = new JB721TiersHookDeployer(EXAMPLE_HOOK, HOOK_STORE, ADDRESS_REGISTRY, multisig());
237
- PUBLISHER = new CTPublisher(jbDirectory(), jbPermissions(), FEE_PROJECT_ID, multisig());
238
- MOCK_BUYBACK = new MockBuybackDataHook();
239
-
240
- LOANS_CONTRACT = new REVLoans({
241
- controller: jbController(),
242
- suckerRegistry: IJBSuckerRegistry(address(new MockSuckerRegistry())),
243
- revId: FEE_PROJECT_ID,
244
- owner: address(this),
245
- permit2: permit2(),
246
- trustedForwarder: TRUSTED_FORWARDER
247
- });
248
-
249
- REV_OWNER = new REVOwner(
250
- IJBBuybackHookRegistry(address(MOCK_BUYBACK)),
251
- jbDirectory(),
252
- FEE_PROJECT_ID,
253
- SUCKER_REGISTRY,
254
- address(LOANS_CONTRACT),
255
- address(0)
256
- );
257
-
258
- REV_DEPLOYER = new REVDeployer{salt: REV_DEPLOYER_SALT}(
259
- jbController(),
260
- SUCKER_REGISTRY,
261
- FEE_PROJECT_ID,
262
- HOOK_DEPLOYER,
263
- PUBLISHER,
264
- IJBBuybackHookRegistry(address(MOCK_BUYBACK)),
265
- address(LOANS_CONTRACT),
266
- TRUSTED_FORWARDER,
267
- address(REV_OWNER)
268
- );
269
-
270
- REV_OWNER.setDeployer(REV_DEPLOYER);
271
-
272
- // Deploy fee project.
273
- vm.prank(multisig());
274
- jbProjects().approve(address(REV_DEPLOYER), FEE_PROJECT_ID);
275
-
276
- SourceFeeProjectConfig memory feeProjectConfig = _getFeeProjectConfig();
277
- vm.prank(multisig());
278
- REV_DEPLOYER.deployFor({
279
- revnetId: FEE_PROJECT_ID,
280
- configuration: feeProjectConfig.configuration,
281
- terminalConfigurations: feeProjectConfig.terminalConfigurations,
282
- suckerDeploymentConfiguration: feeProjectConfig.suckerDeploymentConfiguration,
283
- tiered721HookConfiguration: REVEmpty721Config.empty721Config(uint32(uint160(JBConstants.NATIVE_TOKEN))),
284
- allowedPosts: REVEmpty721Config.emptyAllowedPosts()
285
- });
286
-
287
- // Deploy revnet with loans enabled.
288
- SourceFeeProjectConfig memory revnetConfig = _getRevnetConfig();
289
- (REVNET_ID,) = REV_DEPLOYER.deployFor({
290
- revnetId: 0,
291
- configuration: revnetConfig.configuration,
292
- terminalConfigurations: revnetConfig.terminalConfigurations,
293
- suckerDeploymentConfiguration: revnetConfig.suckerDeploymentConfiguration,
294
- tiered721HookConfiguration: REVEmpty721Config.empty721Config(uint32(uint160(JBConstants.NATIVE_TOKEN))),
295
- allowedPosts: REVEmpty721Config.emptyAllowedPosts()
296
- });
297
-
298
- vm.deal(USER, 1000e18);
299
- }
300
-
301
- // =========================================================================
302
- // Helpers
303
- // =========================================================================
304
-
305
- function _mockLoanPermission(address user) internal {
306
- // Use vm.mockCall (not mockExpect) to avoid enforcing call counts — repay doesn't always
307
- // trigger a permission check, but borrow does.
308
- vm.mockCall(
309
- address(jbPermissions()),
310
- abi.encodeCall(IJBPermissions.hasPermission, (address(LOANS_CONTRACT), user, REVNET_ID, 11, true, true)),
311
- abi.encode(true)
312
- );
313
- }
314
-
315
- function _borrowLoan(address user, uint256 ethAmount) internal returns (uint256 loanId, uint256 tokenCount) {
316
- vm.prank(user);
317
- tokenCount =
318
- jbMultiTerminal().pay{value: ethAmount}(REVNET_ID, JBConstants.NATIVE_TOKEN, ethAmount, user, 0, "", "");
319
-
320
- _mockLoanPermission(user);
321
- REVLoanSource memory source = REVLoanSource({token: JBConstants.NATIVE_TOKEN, terminal: jbMultiTerminal()});
322
-
323
- vm.prank(user);
324
- (loanId,) = LOANS_CONTRACT.borrowFrom(REVNET_ID, source, 0, tokenCount, payable(user), 25, user);
325
- }
326
-
327
- // =========================================================================
328
- // Test: Source fee try-catch during repay — terminal pay reverts
329
- // =========================================================================
330
-
331
- /// @notice When the source terminal's pay() reverts during repay, the source fee is returned
332
- /// to the borrower and the repayment still succeeds.
333
- function test_sourceFeeRecovery_repay_nativeToken() public {
334
- // Step 1: Borrow normally.
335
- (uint256 loanId,) = _borrowLoan(USER, 10e18);
336
-
337
- // Step 2: Read the loan to get prepaid duration.
338
- REVLoan memory loan = LOANS_CONTRACT.loanOf(loanId);
339
-
340
- // Step 3: Warp past the prepaid duration so the source fee accrues.
341
- vm.warp(block.timestamp + loan.prepaidDuration + 30 days);
342
-
343
- // Step 4: Mock the source terminal's pay() to revert.
344
- // This affects only `pay` calls, not `addToBalanceOf` (used by _removeFrom).
345
- vm.mockCallRevert(
346
- address(jbMultiTerminal()), abi.encodeWithSelector(IJBTerminal.pay.selector), "Source fee terminal failed"
347
- );
348
-
349
- // Step 5: Repay the full loan. The source fee try-catch should handle the reverting terminal.
350
- uint256 repayAmount = loan.amount * 2; // Send more than enough to cover loan + fee.
351
- vm.deal(USER, repayAmount);
352
-
353
- vm.prank(USER);
354
- LOANS_CONTRACT.repayLoan{value: repayAmount}({
355
- loanId: loanId,
356
- maxRepayBorrowAmount: repayAmount,
357
- collateralCountToReturn: loan.collateral,
358
- beneficiary: payable(USER),
359
- allowance: JBSingleAllowance({amount: 0, expiration: 0, nonce: 0, sigDeadline: 0, signature: ""})
360
- });
361
-
362
- // Repay succeeded — the loan should be closed.
363
- REVLoan memory postRepay = LOANS_CONTRACT.loanOf(loanId);
364
- assertEq(postRepay.createdAt, 0, "Loan should be cleared after repay");
365
-
366
- // No ETH stuck in loans contract.
367
- assertEq(address(LOANS_CONTRACT).balance, 0, "No ETH stuck in loans contract");
368
- }
369
-
370
- /// @notice When the source terminal's pay() works normally during repay, the source fee is
371
- /// deducted as expected (regression to confirm baseline).
372
- function test_sourceFeePayment_repay_normalOperation() public {
373
- // Borrow normally.
374
- (uint256 loanId,) = _borrowLoan(USER, 10e18);
375
-
376
- REVLoan memory loan = LOANS_CONTRACT.loanOf(loanId);
377
-
378
- // Warp past prepaid duration.
379
- vm.warp(block.timestamp + loan.prepaidDuration + 30 days);
380
-
381
- // Repay normally (no mocking — terminal pay should succeed).
382
- uint256 repayAmount = loan.amount * 2;
383
- vm.deal(USER, repayAmount);
384
-
385
- vm.prank(USER);
386
- LOANS_CONTRACT.repayLoan{value: repayAmount}({
387
- loanId: loanId,
388
- maxRepayBorrowAmount: repayAmount,
389
- collateralCountToReturn: loan.collateral,
390
- beneficiary: payable(USER),
391
- allowance: JBSingleAllowance({amount: 0, expiration: 0, nonce: 0, sigDeadline: 0, signature: ""})
392
- });
393
-
394
- // Loan closed.
395
- REVLoan memory postRepay = LOANS_CONTRACT.loanOf(loanId);
396
- assertEq(postRepay.createdAt, 0, "Loan should be cleared after normal repay");
397
-
398
- // No ETH stuck.
399
- assertEq(address(LOANS_CONTRACT).balance, 0, "No ETH stuck");
400
- }
401
-
402
- /// @notice When the source terminal reverts, the borrower receives more ETH back than when
403
- /// it succeeds, because the source fee is returned to them.
404
- function test_sourceFeeRecovery_borrowerGetsMoreThanNormal() public {
405
- // Borrow a loan.
406
- (uint256 loanId,) = _borrowLoan(USER, 10e18);
407
-
408
- REVLoan memory loan = LOANS_CONTRACT.loanOf(loanId);
409
-
410
- // Warp past prepaid duration.
411
- vm.warp(block.timestamp + loan.prepaidDuration + 30 days);
412
-
413
- // Compute the expected source fee.
414
- uint256 sourceFee = LOANS_CONTRACT.determineSourceFeeAmount(loan, loan.amount);
415
- assertGt(sourceFee, 0, "Source fee should be nonzero after prepaid duration");
416
-
417
- // Snapshot state to compare normal vs. failed scenarios.
418
- uint256 snap = vm.snapshotState();
419
-
420
- // --- Normal repay ---
421
- uint256 repayAmount = loan.amount * 2;
422
- vm.deal(USER, repayAmount);
423
-
424
- uint256 balBefore = USER.balance;
425
- vm.prank(USER);
426
- LOANS_CONTRACT.repayLoan{value: repayAmount}({
427
- loanId: loanId,
428
- maxRepayBorrowAmount: repayAmount,
429
- collateralCountToReturn: loan.collateral,
430
- beneficiary: payable(USER),
431
- allowance: JBSingleAllowance({amount: 0, expiration: 0, nonce: 0, sigDeadline: 0, signature: ""})
432
- });
433
- uint256 normalBalance = USER.balance;
434
-
435
- // --- Revert and try with failing terminal ---
436
- vm.revertToState(snap);
437
-
438
- vm.mockCallRevert(
439
- address(jbMultiTerminal()), abi.encodeWithSelector(IJBTerminal.pay.selector), "Source fee terminal failed"
440
- );
441
-
442
- vm.deal(USER, repayAmount);
443
-
444
- balBefore = USER.balance;
445
- vm.prank(USER);
446
- LOANS_CONTRACT.repayLoan{value: repayAmount}({
447
- loanId: loanId,
448
- maxRepayBorrowAmount: repayAmount,
449
- collateralCountToReturn: loan.collateral,
450
- beneficiary: payable(USER),
451
- allowance: JBSingleAllowance({amount: 0, expiration: 0, nonce: 0, sigDeadline: 0, signature: ""})
452
- });
453
- uint256 failBalance = USER.balance;
454
-
455
- // The borrower should have more ETH when the source fee terminal fails,
456
- // because the source fee is returned to them instead of being paid.
457
- assertGt(failBalance, normalBalance, "Borrower should receive more when source fee terminal fails");
458
- }
459
-
460
- /// @notice Source fee is zero during the prepaid window — no try-catch path is hit.
461
- function test_noSourceFeeDuringPrepaidWindow() public {
462
- (uint256 loanId,) = _borrowLoan(USER, 10e18);
463
-
464
- REVLoan memory loan = LOANS_CONTRACT.loanOf(loanId);
465
-
466
- // Stay within prepaid duration — no source fee accrues.
467
- vm.warp(block.timestamp + loan.prepaidDuration / 2);
468
-
469
- uint256 sourceFee = LOANS_CONTRACT.determineSourceFeeAmount(loan, loan.amount);
470
- assertEq(sourceFee, 0, "No source fee during prepaid window");
471
-
472
- // Repay during prepaid window.
473
- uint256 repayAmount = loan.amount * 2;
474
- vm.deal(USER, repayAmount);
475
-
476
- vm.prank(USER);
477
- LOANS_CONTRACT.repayLoan{value: repayAmount}({
478
- loanId: loanId,
479
- maxRepayBorrowAmount: repayAmount,
480
- collateralCountToReturn: loan.collateral,
481
- beneficiary: payable(USER),
482
- allowance: JBSingleAllowance({amount: 0, expiration: 0, nonce: 0, sigDeadline: 0, signature: ""})
483
- });
484
-
485
- REVLoan memory postRepay = LOANS_CONTRACT.loanOf(loanId);
486
- assertEq(postRepay.createdAt, 0, "Loan should be cleared");
487
- assertEq(address(LOANS_CONTRACT).balance, 0, "No ETH stuck");
488
- }
489
-
490
- /// @notice The source fee try-catch during initial borrow (prepaid source fee) also recovers
491
- /// gracefully when the source terminal reverts.
492
- function test_sourceFeeRecovery_initialBorrow() public {
493
- // Pay into the revnet first.
494
- vm.prank(USER);
495
- uint256 tokenCount =
496
- jbMultiTerminal().pay{value: 10e18}(REVNET_ID, JBConstants.NATIVE_TOKEN, 10e18, USER, 0, "", "");
497
-
498
- // Now mock the source terminal's pay to revert (for source fee payment).
499
- // This will also cause the REV fee payment to fail (same terminal), but both are try-caught.
500
- vm.mockCallRevert(
501
- address(jbMultiTerminal()), abi.encodeWithSelector(IJBTerminal.pay.selector), "Terminal pay failed"
502
- );
503
-
504
- _mockLoanPermission(USER);
505
- REVLoanSource memory source = REVLoanSource({token: JBConstants.NATIVE_TOKEN, terminal: jbMultiTerminal()});
506
-
507
- uint256 balBefore = USER.balance;
508
- vm.prank(USER);
509
- LOANS_CONTRACT.borrowFrom(REVNET_ID, source, 0, tokenCount, payable(USER), 25, USER);
510
-
511
- uint256 received = USER.balance - balBefore;
512
- assertGt(received, 0, "Borrower should receive ETH even when source fee terminal fails");
513
-
514
- // No ETH stuck.
515
- assertEq(address(LOANS_CONTRACT).balance, 0, "No ETH stuck in loans contract");
516
- }
517
- }