@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,412 +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
- // forge-lint: disable-next-line(unaliased-plain-import)
14
- import "@bananapus/core-v6/script/helpers/CoreDeploymentLib.sol";
15
- // forge-lint: disable-next-line(unaliased-plain-import)
16
- import "@bananapus/721-hook-v6/script/helpers/Hook721DeploymentLib.sol";
17
- // forge-lint: disable-next-line(unaliased-plain-import)
18
- import "@bananapus/suckers-v6/script/helpers/SuckerDeploymentLib.sol";
19
- // forge-lint: disable-next-line(unaliased-plain-import)
20
- import "@croptop/core-v6/script/helpers/CroptopDeploymentLib.sol";
21
- // forge-lint: disable-next-line(unaliased-plain-import)
22
- import "@bananapus/router-terminal-v6/script/helpers/RouterTerminalDeploymentLib.sol";
23
- import {JBConstants} from "@bananapus/core-v6/src/libraries/JBConstants.sol";
24
- import {JBAccountingContext} from "@bananapus/core-v6/src/structs/JBAccountingContext.sol";
25
- import {JBPermissionIds} from "@bananapus/permission-ids-v6/src/JBPermissionIds.sol";
26
- import {REVLoans} from "../src/REVLoans.sol";
27
- import {REVLoan} from "../src/structs/REVLoan.sol";
28
- import {REVStageConfig, REVAutoIssuance} from "../src/structs/REVStageConfig.sol";
29
- import {REVLoanSource} from "../src/structs/REVLoanSource.sol";
30
- import {REVDescription} from "../src/structs/REVDescription.sol";
31
- import {IREVLoans} from "./../src/interfaces/IREVLoans.sol";
32
- import {JBSuckerDeployerConfig} from "@bananapus/suckers-v6/src/structs/JBSuckerDeployerConfig.sol";
33
- import {JBSuckerRegistry} from "@bananapus/suckers-v6/src/JBSuckerRegistry.sol";
34
- import {JB721TiersHookDeployer} from "@bananapus/721-hook-v6/src/JB721TiersHookDeployer.sol";
35
- import {JB721TiersHook} from "@bananapus/721-hook-v6/src/JB721TiersHook.sol";
36
- import {JB721TiersHookStore} from "@bananapus/721-hook-v6/src/JB721TiersHookStore.sol";
37
- import {JB721CheckpointsDeployer} from "@bananapus/721-hook-v6/src/JB721CheckpointsDeployer.sol";
38
- import {IJB721CheckpointsDeployer} from "@bananapus/721-hook-v6/src/interfaces/IJB721CheckpointsDeployer.sol";
39
- import {JBAddressRegistry} from "@bananapus/address-registry-v6/src/JBAddressRegistry.sol";
40
- import {IJBAddressRegistry} from "@bananapus/address-registry-v6/src/interfaces/IJBAddressRegistry.sol";
41
- import {REVEmpty721Config} from "./helpers/REVEmpty721Config.sol";
42
- import {REVOwner} from "../src/REVOwner.sol";
43
- import {IREVDeployer} from "../src/interfaces/IREVDeployer.sol";
44
- import {MockSuckerRegistry} from "./mock/MockSuckerRegistry.sol";
45
-
46
- /// @notice Deterministic test for the reallocation sandwich at stage boundaries.
47
- /// Documents that a borrower can extract additional value by calling `reallocateCollateralFromLoan` immediately
48
- /// after a stage transition that lowers the `cashOutTaxRate`. This is intentional design behavior:
49
- /// loan value tracks the current bonding curve parameters, and stage boundaries are immutable and predictable.
50
- /// See RISKS.md section 3 ("reallocateCollateralFromLoan sandwich potential") for details.
51
- contract TestReallocationSandwich is TestBaseWorkflow {
52
- // forge-lint: disable-next-line(mixed-case-variable)
53
- bytes32 REV_DEPLOYER_SALT = "REVDeployer";
54
-
55
- // forge-lint: disable-next-line(mixed-case-variable)
56
- REVDeployer REV_DEPLOYER;
57
- // forge-lint: disable-next-line(mixed-case-variable)
58
- REVOwner REV_OWNER;
59
- // forge-lint: disable-next-line(mixed-case-variable)
60
- JB721TiersHook EXAMPLE_HOOK;
61
- // forge-lint: disable-next-line(mixed-case-variable)
62
- IJB721TiersHookDeployer HOOK_DEPLOYER;
63
- // forge-lint: disable-next-line(mixed-case-variable)
64
- IJB721TiersHookStore HOOK_STORE;
65
- // forge-lint: disable-next-line(mixed-case-variable)
66
- IJBAddressRegistry ADDRESS_REGISTRY;
67
- // forge-lint: disable-next-line(mixed-case-variable)
68
- IREVLoans LOANS_CONTRACT;
69
- // forge-lint: disable-next-line(mixed-case-variable)
70
- IJBSuckerRegistry SUCKER_REGISTRY;
71
- // forge-lint: disable-next-line(mixed-case-variable)
72
- CTPublisher PUBLISHER;
73
- // forge-lint: disable-next-line(mixed-case-variable)
74
- MockBuybackDataHook MOCK_BUYBACK;
75
-
76
- // forge-lint: disable-next-line(mixed-case-variable)
77
- uint256 FEE_PROJECT_ID;
78
- // forge-lint: disable-next-line(mixed-case-variable)
79
- uint256 REVNET_ID;
80
-
81
- // forge-lint: disable-next-line(mixed-case-variable)
82
- address BORROWER = makeAddr("borrower");
83
- // forge-lint: disable-next-line(mixed-case-variable)
84
- address OTHER_PAYER = makeAddr("otherPayer");
85
-
86
- address private constant TRUSTED_FORWARDER = 0xB2b5841DBeF766d4b521221732F9B618fCf34A87;
87
-
88
- /// @notice Stage 1 starts now with 60% cashOutTaxRate, stage 2 starts after 30 days with 20% cashOutTaxRate.
89
- function _buildConfig()
90
- internal
91
- view
92
- returns (REVConfig memory cfg, JBTerminalConfig[] memory tc, REVSuckerDeploymentConfig memory sdc)
93
- {
94
- JBAccountingContext[] memory acc = new JBAccountingContext[](1);
95
- acc[0] = JBAccountingContext({
96
- token: JBConstants.NATIVE_TOKEN, decimals: 18, currency: uint32(uint160(JBConstants.NATIVE_TOKEN))
97
- });
98
- tc = new JBTerminalConfig[](1);
99
- tc[0] = JBTerminalConfig({terminal: jbMultiTerminal(), accountingContextsToAccept: acc});
100
-
101
- REVStageConfig[] memory stages = new REVStageConfig[](2);
102
- JBSplit[] memory splits = new JBSplit[](1);
103
- splits[0].beneficiary = payable(multisig());
104
- splits[0].percent = 10_000;
105
-
106
- // Stage 1: high cashOutTaxRate (60%)
107
- stages[0] = REVStageConfig({
108
- startsAtOrAfter: uint40(block.timestamp),
109
- autoIssuances: new REVAutoIssuance[](0),
110
- splitPercent: 0,
111
- splits: splits,
112
- initialIssuance: uint112(1000e18),
113
- issuanceCutFrequency: 0,
114
- issuanceCutPercent: 0,
115
- cashOutTaxRate: 6000, // 60%
116
- extraMetadata: 0
117
- });
118
-
119
- // Stage 2: low cashOutTaxRate (20%) -- starts after 30 days
120
- stages[1] = REVStageConfig({
121
- startsAtOrAfter: uint40(block.timestamp + 30 days),
122
- autoIssuances: new REVAutoIssuance[](0),
123
- splitPercent: 0,
124
- splits: splits,
125
- initialIssuance: uint112(1000e18),
126
- issuanceCutFrequency: 0,
127
- issuanceCutPercent: 0,
128
- cashOutTaxRate: 2000, // 20%
129
- extraMetadata: 0
130
- });
131
-
132
- cfg = REVConfig({
133
- // forge-lint: disable-next-line(named-struct-fields)
134
- description: REVDescription("SandwichTest", "SWT", "ipfs://sandwich", "SWT_SALT"),
135
- baseCurrency: uint32(uint160(JBConstants.NATIVE_TOKEN)),
136
- splitOperator: multisig(),
137
- stageConfigurations: stages
138
- });
139
-
140
- sdc = REVSuckerDeploymentConfig({
141
- deployerConfigurations: new JBSuckerDeployerConfig[](0), salt: keccak256(abi.encodePacked("SWT"))
142
- });
143
- }
144
-
145
- function setUp() public override {
146
- super.setUp();
147
- FEE_PROJECT_ID = jbProjects().createFor(multisig());
148
- SUCKER_REGISTRY = new JBSuckerRegistry(jbDirectory(), jbPermissions(), multisig(), address(0));
149
- HOOK_STORE = new JB721TiersHookStore();
150
- EXAMPLE_HOOK = new JB721TiersHook(
151
- jbDirectory(),
152
- jbPermissions(),
153
- jbPrices(),
154
- jbRulesets(),
155
- HOOK_STORE,
156
- jbSplits(),
157
- IJB721CheckpointsDeployer(address(new JB721CheckpointsDeployer())),
158
- multisig()
159
- );
160
- ADDRESS_REGISTRY = new JBAddressRegistry();
161
- HOOK_DEPLOYER = new JB721TiersHookDeployer(EXAMPLE_HOOK, HOOK_STORE, ADDRESS_REGISTRY, multisig());
162
- PUBLISHER = new CTPublisher(jbDirectory(), jbPermissions(), FEE_PROJECT_ID, multisig());
163
- MOCK_BUYBACK = new MockBuybackDataHook();
164
- LOANS_CONTRACT = new REVLoans({
165
- controller: jbController(),
166
- suckerRegistry: IJBSuckerRegistry(address(new MockSuckerRegistry())),
167
- revId: FEE_PROJECT_ID,
168
- owner: address(this),
169
- permit2: permit2(),
170
- trustedForwarder: TRUSTED_FORWARDER
171
- });
172
- REV_OWNER = new REVOwner(
173
- IJBBuybackHookRegistry(address(MOCK_BUYBACK)),
174
- jbDirectory(),
175
- FEE_PROJECT_ID,
176
- SUCKER_REGISTRY,
177
- address(LOANS_CONTRACT),
178
- address(0)
179
- );
180
-
181
- REV_DEPLOYER = new REVDeployer{salt: REV_DEPLOYER_SALT}(
182
- jbController(),
183
- SUCKER_REGISTRY,
184
- FEE_PROJECT_ID,
185
- HOOK_DEPLOYER,
186
- PUBLISHER,
187
- IJBBuybackHookRegistry(address(MOCK_BUYBACK)),
188
- address(LOANS_CONTRACT),
189
- TRUSTED_FORWARDER,
190
- address(REV_OWNER)
191
- );
192
-
193
- REV_OWNER.setDeployer(REV_DEPLOYER);
194
-
195
- vm.prank(multisig());
196
- jbProjects().approve(address(REV_DEPLOYER), FEE_PROJECT_ID);
197
-
198
- // Deploy the fee project first.
199
- (REVConfig memory feeCfg, JBTerminalConfig[] memory feeTc, REVSuckerDeploymentConfig memory feeSdc) =
200
- _buildConfig();
201
- vm.prank(multisig());
202
- REV_DEPLOYER.deployFor({
203
- revnetId: FEE_PROJECT_ID,
204
- configuration: feeCfg,
205
- terminalConfigurations: feeTc,
206
- suckerDeploymentConfiguration: feeSdc,
207
- tiered721HookConfiguration: REVEmpty721Config.empty721Config(uint32(uint160(JBConstants.NATIVE_TOKEN))),
208
- allowedPosts: REVEmpty721Config.emptyAllowedPosts()
209
- });
210
-
211
- // Deploy the test revnet.
212
- (REVConfig memory cfg, JBTerminalConfig[] memory tc, REVSuckerDeploymentConfig memory sdc) = _buildConfig();
213
- // forge-lint: disable-next-line(named-struct-fields)
214
- cfg.description = REVDescription("SandwichTest2", "SW2", "ipfs://sandwich2", "SWT_SALT_2");
215
- (REVNET_ID,) = REV_DEPLOYER.deployFor({
216
- revnetId: 0,
217
- configuration: cfg,
218
- terminalConfigurations: tc,
219
- suckerDeploymentConfiguration: sdc,
220
- tiered721HookConfiguration: REVEmpty721Config.empty721Config(uint32(uint160(JBConstants.NATIVE_TOKEN))),
221
- allowedPosts: REVEmpty721Config.emptyAllowedPosts()
222
- });
223
-
224
- vm.deal(BORROWER, 100 ether);
225
- vm.deal(OTHER_PAYER, 100 ether);
226
- }
227
-
228
- /// @notice Helper: grant BURN_TOKENS permission to the loans contract for a given account and revnet.
229
- function _grantBurnPermission(address account, uint256 revnetId) internal {
230
- uint8[] memory permissionIds = new uint8[](1);
231
- permissionIds[0] = JBPermissionIds.BURN_TOKENS;
232
-
233
- JBPermissionsData memory permissionsData = JBPermissionsData({
234
- // forge-lint: disable-next-line(unsafe-typecast)
235
- operator: address(LOANS_CONTRACT),
236
- // forge-lint: disable-next-line(unsafe-typecast)
237
- projectId: uint56(revnetId),
238
- permissionIds: permissionIds
239
- });
240
-
241
- vm.prank(account);
242
- jbPermissions().setPermissionsFor(account, permissionsData);
243
- }
244
-
245
- /// @notice BY DESIGN: A borrower can extract additional value by reallocating collateral immediately after
246
- /// a stage transition that lowers the cashOutTaxRate.
247
- ///
248
- /// The sandwich works as follows:
249
- /// 1. Borrower takes a loan in Stage 1 (60% cashOutTaxRate) — collateral is locked at Stage 1's rate
250
- /// 2. Time warps past the stage boundary to Stage 2 (20% cashOutTaxRate)
251
- /// 3. At Stage 2 rates, the same collateral is worth MORE on the bonding curve, so LESS collateral is
252
- /// needed to support the original loan amount. The borrower frees the excess collateral.
253
- /// 4. The freed collateral is used to open a NEW loan at Stage 2 rates — extracting additional funds.
254
- /// 5. The borrower now holds TWO loans: the original (with reduced collateral) and a new one (with the
255
- /// freed collateral). The total borrowed across both loans exceeds what was possible at Stage 1.
256
- ///
257
- /// This is intentional: stage boundaries are immutable and predictable, and loan value tracks
258
- /// the current bonding curve parameters. See RISKS.md section 3.
259
- function test_reallocationSandwich_extractsValueAtStageBoundary() public {
260
- // -- Step 1: Create liquidity from another payer so the bonding curve tax rate has a visible effect.
261
- vm.prank(OTHER_PAYER);
262
- jbMultiTerminal().pay{value: 10 ether}({
263
- projectId: REVNET_ID,
264
- token: JBConstants.NATIVE_TOKEN,
265
- amount: 10 ether,
266
- beneficiary: OTHER_PAYER,
267
- minReturnedTokens: 0,
268
- memo: "",
269
- metadata: ""
270
- });
271
-
272
- // -- Step 2: Borrower pays in and receives tokens during Stage 1.
273
- vm.prank(BORROWER);
274
- uint256 borrowerTokens = jbMultiTerminal().pay{value: 10 ether}({
275
- projectId: REVNET_ID,
276
- token: JBConstants.NATIVE_TOKEN,
277
- amount: 10 ether,
278
- beneficiary: BORROWER,
279
- minReturnedTokens: 0,
280
- memo: "",
281
- metadata: ""
282
- });
283
- assertGt(borrowerTokens, 0, "Borrower should receive tokens");
284
-
285
- // -- Step 3: Grant BURN_TOKENS permission and take a loan during Stage 1.
286
- _grantBurnPermission(BORROWER, REVNET_ID);
287
-
288
- REVLoanSource memory source = REVLoanSource({token: JBConstants.NATIVE_TOKEN, terminal: jbMultiTerminal()});
289
-
290
- // Use the minimum prepaid fee (2.5%) so fees don't obscure the comparison.
291
- uint256 prepaidFeePercent = LOANS_CONTRACT.MIN_PREPAID_FEE_PERCENT();
292
-
293
- vm.prank(BORROWER);
294
- (uint256 stage1LoanId, REVLoan memory stage1Loan) = LOANS_CONTRACT.borrowFrom({
295
- revnetId: REVNET_ID,
296
- source: source,
297
- minBorrowAmount: 0,
298
- collateralCount: borrowerTokens,
299
- beneficiary: payable(BORROWER),
300
- prepaidFeePercent: prepaidFeePercent,
301
- holder: BORROWER
302
- });
303
-
304
- uint256 stage1BorrowedAmount = stage1Loan.amount;
305
- uint256 stage1Collateral = stage1Loan.collateral;
306
- assertGt(stage1BorrowedAmount, 0, "Stage 1 loan should have positive borrowed amount");
307
- assertEq(stage1Collateral, borrowerTokens, "All tokens should be collateral");
308
-
309
- // Record the borrowable amount for the same collateral count at Stage 1 rates (for comparison).
310
- uint256 borrowableStage1 = LOANS_CONTRACT.borrowableAmountFrom(
311
- REVNET_ID, borrowerTokens, 18, uint32(uint160(JBConstants.NATIVE_TOKEN))
312
- );
313
-
314
- // -- Step 4: Warp past the stage boundary to Stage 2 (lower cashOutTaxRate).
315
- vm.warp(block.timestamp + 31 days);
316
-
317
- // Verify borrowable amount increased at Stage 2 rates.
318
- uint256 borrowableStage2 = LOANS_CONTRACT.borrowableAmountFrom(
319
- REVNET_ID, borrowerTokens, 18, uint32(uint160(JBConstants.NATIVE_TOKEN))
320
- );
321
- assertGt(borrowableStage2, borrowableStage1, "Borrowable should increase with lower cashOutTaxRate");
322
-
323
- // -- Step 5: Determine how much collateral can be freed.
324
- // At Stage 2's lower cashOutTaxRate, less collateral is needed to support the original loan amount.
325
- // Use binary search to find the maximum transferable collateral: the largest amount that can be
326
- // removed while leaving enough for the remaining collateral to cover the original loan amount.
327
- uint256 collateralToTransfer;
328
- {
329
- uint256 lo = 0;
330
- uint256 hi = stage1Collateral;
331
- uint256 currency = uint32(uint160(JBConstants.NATIVE_TOKEN));
332
- while (lo < hi) {
333
- uint256 mid = (lo + hi + 1) / 2;
334
- uint256 remaining = stage1Collateral - mid;
335
- uint256 borrowable = LOANS_CONTRACT.borrowableAmountFrom(REVNET_ID, remaining, 18, currency);
336
- if (borrowable >= stage1BorrowedAmount) {
337
- lo = mid;
338
- } else {
339
- hi = mid - 1;
340
- }
341
- }
342
- collateralToTransfer = lo;
343
- }
344
- assertGt(collateralToTransfer, 0, "Should be able to free some collateral after tax rate decrease");
345
-
346
- // Verify that the remaining collateral at Stage 2 rates supports the original loan amount.
347
- uint256 borrowableWithRemaining = LOANS_CONTRACT.borrowableAmountFrom(
348
- REVNET_ID, stage1Collateral - collateralToTransfer, 18, uint32(uint160(JBConstants.NATIVE_TOKEN))
349
- );
350
- assertGe(
351
- borrowableWithRemaining,
352
- stage1BorrowedAmount,
353
- "Remaining collateral should cover original loan at Stage 2 rates"
354
- );
355
-
356
- // -- Step 6: Borrower reallocates collateral from the Stage 1 loan to extract the increased value.
357
- // Transfer half the collateral from the old loan. The remaining half still covers the original
358
- // loan amount at Stage 2's improved rates. The freed collateral goes into a new loan.
359
- vm.prank(BORROWER);
360
- (
361
- , // reallocatedLoanId
362
- , // newLoanId
363
- REVLoan memory reallocatedLoan,
364
- REVLoan memory newLoan
365
- ) = LOANS_CONTRACT.reallocateCollateralFromLoan({
366
- loanId: stage1LoanId,
367
- collateralCountToTransfer: collateralToTransfer,
368
- source: source,
369
- minBorrowAmount: 0,
370
- collateralCountToAdd: 0,
371
- beneficiary: payable(BORROWER),
372
- prepaidFeePercent: prepaidFeePercent
373
- });
374
-
375
- // -- Step 7: Verify the sandwich extracted additional value.
376
-
377
- // The reallocated loan retains the original borrowed amount with reduced collateral.
378
- assertEq(reallocatedLoan.amount, stage1BorrowedAmount, "Reallocated loan should keep original amount");
379
- assertEq(
380
- reallocatedLoan.collateral,
381
- stage1Collateral - collateralToTransfer,
382
- "Reallocated loan should have reduced collateral"
383
- );
384
-
385
- // The new loan was created from the freed collateral at Stage 2 rates.
386
- uint256 newBorrowedAmount = newLoan.amount;
387
- assertGt(newBorrowedAmount, 0, "New loan should have positive borrowed amount");
388
- assertEq(newLoan.collateral, collateralToTransfer, "New loan should hold the transferred collateral");
389
-
390
- // The total borrowed across both loans exceeds the original Stage 1 borrowed amount.
391
- // This is the sandwich profit: the borrower extracted additional value from the same total collateral.
392
- uint256 totalBorrowedAfterSandwich = uint256(reallocatedLoan.amount) + uint256(newLoan.amount);
393
- assertGt(
394
- totalBorrowedAfterSandwich,
395
- stage1BorrowedAmount,
396
- "Total borrowed after sandwich should exceed original Stage 1 amount"
397
- );
398
-
399
- // Quantify the extracted delta.
400
- uint256 extractedDelta = totalBorrowedAfterSandwich - stage1BorrowedAmount;
401
- assertGt(extractedDelta, 0, "Extracted delta should be positive");
402
-
403
- // Log the sandwich economics for visibility.
404
- emit log_named_uint("Stage 1 borrowed amount", stage1BorrowedAmount);
405
- emit log_named_uint("Reallocated loan amount (unchanged)", reallocatedLoan.amount);
406
- emit log_named_uint("New loan amount (from freed collateral)", newBorrowedAmount);
407
- emit log_named_uint("Total borrowed after sandwich", totalBorrowedAfterSandwich);
408
- emit log_named_uint("Extracted delta (sandwich profit)", extractedDelta);
409
- emit log_named_uint("Borrowable at Stage 1 rates (full collateral)", borrowableStage1);
410
- emit log_named_uint("Borrowable at Stage 2 rates (full collateral)", borrowableStage2);
411
- }
412
- }