@bananapus/core-v6 0.0.16 → 0.0.17

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 (43) hide show
  1. package/ADMINISTRATION.md +1 -1
  2. package/ARCHITECTURE.md +2 -1
  3. package/AUDIT_INSTRUCTIONS.md +342 -0
  4. package/CHANGE_LOG.md +375 -0
  5. package/README.md +4 -4
  6. package/RISKS.md +171 -50
  7. package/SKILLS.md +9 -6
  8. package/USER_JOURNEYS.md +622 -0
  9. package/package.json +2 -2
  10. package/script/DeployPeriphery.s.sol +7 -1
  11. package/src/JBController.sol +5 -0
  12. package/src/JBDeadline.sol +3 -0
  13. package/src/JBDirectory.sol +2 -1
  14. package/src/JBMultiTerminal.sol +50 -9
  15. package/src/JBPermissions.sol +2 -0
  16. package/src/JBPrices.sol +8 -2
  17. package/src/JBRulesets.sol +3 -0
  18. package/src/JBSplits.sol +9 -5
  19. package/src/JBTerminalStore.sol +54 -47
  20. package/src/JBTokens.sol +3 -0
  21. package/src/interfaces/IJBTerminalStore.sol +3 -0
  22. package/src/libraries/JBFees.sol +2 -0
  23. package/src/libraries/JBMetadataResolver.sol +17 -4
  24. package/src/structs/JBBeforeCashOutRecordedContext.sol +4 -0
  25. package/test/TestAuditResponseDesignProofs.sol +434 -0
  26. package/test/TestDataHookFuzzing.sol +520 -0
  27. package/test/TestFeeFreeCashOutBypass.sol +617 -0
  28. package/test/TestL2SequencerPriceFeed.sol +292 -0
  29. package/test/TestMetadataOffsetOverflow.sol +179 -0
  30. package/test/TestMultiTerminalSurplus.sol +348 -0
  31. package/test/TestPermit2DataHook.t.sol +360 -0
  32. package/test/TestRulesetQueueing.sol +1 -2
  33. package/test/TestRulesetWeightCaching.sol +122 -124
  34. package/test/WeirdTokenTests.t.sol +37 -0
  35. package/test/regression/HoldFeesCashOutReserved.t.sol +415 -0
  36. package/test/regression/WeightCacheBoundary.t.sol +291 -0
  37. package/test/units/static/JBMultiTerminal/TestAddToBalanceOf.sol +2 -2
  38. package/test/units/static/JBMultiTerminal/TestCashOutTokensOf.sol +18 -17
  39. package/test/units/static/JBMultiTerminal/TestPay.sol +6 -4
  40. package/test/units/static/JBMultiTerminal/TestProcessHeldFeesOf.sol +206 -18
  41. package/test/units/static/JBMultiTerminal/TestUseAllowanceOf.sol +280 -0
  42. package/test/units/static/JBSplits/TestSelfManagedSplitGroups.sol +55 -12
  43. package/test/units/static/JBTerminalStore/TestRecordCashOutsFor.sol +72 -0
@@ -175,6 +175,14 @@ contract WeirdTokenTests_Local is TestBaseWorkflow {
175
175
  // 1% fee: 1000e18 * 99/100 = 990e18
176
176
  uint256 expectedDelta = 990e18;
177
177
  assertEq(recordedBalance, expectedDelta, "Terminal should record delta amount for FOT tokens");
178
+
179
+ // INVARIANT: recorded balance <= actual token balance at all times.
180
+ uint256 actualTerminalBalance = fotToken.balanceOf(address(jbMultiTerminal()));
181
+ assertLe(
182
+ recordedBalance,
183
+ actualTerminalBalance,
184
+ "FOT: recorded balance must not exceed actual terminal token balance after pay"
185
+ );
178
186
  }
179
187
 
180
188
  // ═══════════════════════════════════════════════════════════════════
@@ -223,6 +231,16 @@ contract WeirdTokenTests_Local is TestBaseWorkflow {
223
231
 
224
232
  // Beneficiary receives less than reclaimAmount due to outbound fee
225
233
  assertLt(actualReceived, reclaimAmount, "FOT: beneficiary receives less than reclaimAmount on outbound");
234
+
235
+ // INVARIANT: recorded balance <= actual token balance after cash-out.
236
+ uint256 recordedBalanceAfterCashOut =
237
+ jbTerminalStore().balanceOf(address(jbMultiTerminal()), pid, address(fotToken));
238
+ uint256 actualTerminalBalanceAfterCashOut = fotToken.balanceOf(address(jbMultiTerminal()));
239
+ assertLe(
240
+ recordedBalanceAfterCashOut,
241
+ actualTerminalBalanceAfterCashOut,
242
+ "FOT: recorded balance must not exceed actual terminal token balance after cash-out"
243
+ );
226
244
  }
227
245
 
228
246
  // ═══════════════════════════════════════════════════════════════════
@@ -336,6 +354,17 @@ contract WeirdTokenTests_Local is TestBaseWorkflow {
336
354
  assertTrue(actualReceived > 0, "Split beneficiary should receive something");
337
355
  // The terminal sends a computed net amount, but the FOT tax reduces what arrives
338
356
  // This documents the information finding: FOT tokens cause split recipients to receive less
357
+
358
+ // INVARIANT: Terminal's recorded balance must never exceed actual token balance.
359
+ // With FOT tokens, the terminal may hold fewer tokens than recorded (inbound fee on pay).
360
+ // After a payout, the recorded balance should still be <= actual balance.
361
+ uint256 recordedBalance = jbTerminalStore().balanceOf(address(jbMultiTerminal()), pid, address(fotToken));
362
+ uint256 actualTerminalBalance = fotToken.balanceOf(address(jbMultiTerminal()));
363
+ assertLe(
364
+ recordedBalance,
365
+ actualTerminalBalance,
366
+ "FOT: recorded balance must not exceed actual terminal token balance after payout"
367
+ );
339
368
  }
340
369
 
341
370
  // ═══════════════════════════════════════════════════════════════════
@@ -574,6 +603,14 @@ contract WeirdTokenTests_Local is TestBaseWorkflow {
574
603
 
575
604
  // Balance should increase (delta accounting handles the fee)
576
605
  assertGt(recordedAfter, recordedBefore, "Balance should increase with addToBalance");
606
+
607
+ // INVARIANT: recorded balance <= actual token balance after addToBalance.
608
+ uint256 actualTerminalBalance = fotToken.balanceOf(address(jbMultiTerminal()));
609
+ assertLe(
610
+ recordedAfter,
611
+ actualTerminalBalance,
612
+ "FOT: recorded balance must not exceed actual terminal token balance after addToBalance"
613
+ );
577
614
  }
578
615
 
579
616
  // ═══════════════════════════════════════════════════════════════════
@@ -0,0 +1,415 @@
1
+ // SPDX-License-Identifier: MIT
2
+ pragma solidity ^0.8.6;
3
+
4
+ import {TestBaseWorkflow} from "../helpers/TestBaseWorkflow.sol";
5
+ import {JBTerminalStore} from "../../src/JBTerminalStore.sol";
6
+ import {JBTokens} from "../../src/JBTokens.sol";
7
+ import {IJBController} from "../../src/interfaces/IJBController.sol";
8
+ import {IJBMultiTerminal} from "../../src/interfaces/IJBMultiTerminal.sol";
9
+ import {IJBRulesetApprovalHook} from "../../src/interfaces/IJBRulesetApprovalHook.sol";
10
+ import {JBConstants} from "../../src/libraries/JBConstants.sol";
11
+ import {JBFees} from "../../src/libraries/JBFees.sol";
12
+ import {JBCashOuts} from "../../src/libraries/JBCashOuts.sol";
13
+ import {JBAccountingContext} from "../../src/structs/JBAccountingContext.sol";
14
+ import {JBCurrencyAmount} from "../../src/structs/JBCurrencyAmount.sol";
15
+ import {JBFee} from "../../src/structs/JBFee.sol";
16
+ import {JBFundAccessLimitGroup} from "../../src/structs/JBFundAccessLimitGroup.sol";
17
+ import {JBRulesetConfig} from "../../src/structs/JBRulesetConfig.sol";
18
+ import {JBRulesetMetadata} from "../../src/structs/JBRulesetMetadata.sol";
19
+ import {JBSplitGroup} from "../../src/structs/JBSplitGroup.sol";
20
+ import {JBTerminalConfig} from "../../src/structs/JBTerminalConfig.sol";
21
+
22
+ /// @notice Regression test for the three-way interaction between holdFees, cashOutTaxRate, and reservedPercent.
23
+ /// Exercises the full lifecycle: pay -> sendPayouts (holding fees) -> cashOut (with tax + pending reserves) ->
24
+ /// distribute reserved tokens, then verifies all accounting invariants hold.
25
+ contract HoldFeesCashOutReserved_Local is TestBaseWorkflow {
26
+ IJBController private _controller;
27
+ IJBMultiTerminal private _terminal;
28
+ JBTokens private _tokens;
29
+ JBTerminalStore private _store;
30
+ uint256 private _projectId;
31
+ address private _projectOwner;
32
+ address private _payer;
33
+
34
+ uint112 private constant WEIGHT = 1000 * 10 ** 18;
35
+ uint112 private constant PAY_AMOUNT = 10 ether;
36
+ uint224 private constant PAYOUT_LIMIT = 2 ether;
37
+
38
+ function setUp() public override {
39
+ super.setUp();
40
+
41
+ _projectOwner = multisig();
42
+ _payer = beneficiary();
43
+ _controller = jbController();
44
+ _terminal = jbMultiTerminal();
45
+ _tokens = jbTokens();
46
+ _store = jbTerminalStore();
47
+
48
+ // Three-way config: holdFees + 50% reservedPercent + 50% cashOutTaxRate.
49
+ JBRulesetMetadata memory metadata = JBRulesetMetadata({
50
+ reservedPercent: 5000, // 50%
51
+ cashOutTaxRate: 5000, // 50%
52
+ baseCurrency: uint32(uint160(JBConstants.NATIVE_TOKEN)),
53
+ pausePay: false,
54
+ pauseCreditTransfers: false,
55
+ allowOwnerMinting: true,
56
+ allowSetCustomToken: false,
57
+ allowTerminalMigration: false,
58
+ allowSetTerminals: false,
59
+ ownerMustSendPayouts: false,
60
+ allowSetController: false,
61
+ allowAddAccountingContext: true,
62
+ allowAddPriceFeed: false,
63
+ holdFees: true,
64
+ useTotalSurplusForCashOuts: false,
65
+ useDataHookForPay: false,
66
+ useDataHookForCashOut: false,
67
+ dataHook: address(0),
68
+ metadata: 0
69
+ });
70
+
71
+ // Payout limit of 2 ETH.
72
+ JBFundAccessLimitGroup[] memory fundAccessLimitGroups = new JBFundAccessLimitGroup[](1);
73
+ {
74
+ JBCurrencyAmount[] memory payoutLimits = new JBCurrencyAmount[](1);
75
+ payoutLimits[0] =
76
+ JBCurrencyAmount({amount: PAYOUT_LIMIT, currency: uint32(uint160(JBConstants.NATIVE_TOKEN))});
77
+ JBCurrencyAmount[] memory surplusAllowances = new JBCurrencyAmount[](1);
78
+ surplusAllowances[0] = JBCurrencyAmount({amount: 0, currency: uint32(uint160(JBConstants.NATIVE_TOKEN))});
79
+ fundAccessLimitGroups[0] = JBFundAccessLimitGroup({
80
+ terminal: address(_terminal),
81
+ token: JBConstants.NATIVE_TOKEN,
82
+ payoutLimits: payoutLimits,
83
+ surplusAllowances: surplusAllowances
84
+ });
85
+ }
86
+
87
+ JBRulesetConfig[] memory rulesetConfig = new JBRulesetConfig[](1);
88
+ rulesetConfig[0].mustStartAtOrAfter = 0;
89
+ rulesetConfig[0].duration = 0;
90
+ rulesetConfig[0].weight = WEIGHT;
91
+ rulesetConfig[0].weightCutPercent = 0;
92
+ rulesetConfig[0].approvalHook = IJBRulesetApprovalHook(address(0));
93
+ rulesetConfig[0].metadata = metadata;
94
+ rulesetConfig[0].splitGroups = new JBSplitGroup[](0);
95
+ rulesetConfig[0].fundAccessLimitGroups = fundAccessLimitGroups;
96
+
97
+ JBTerminalConfig[] memory terminalConfigs = new JBTerminalConfig[](1);
98
+ JBAccountingContext[] memory tokensToAccept = new JBAccountingContext[](1);
99
+ tokensToAccept[0] = JBAccountingContext({
100
+ token: JBConstants.NATIVE_TOKEN, decimals: 18, currency: uint32(uint160(JBConstants.NATIVE_TOKEN))
101
+ });
102
+ terminalConfigs[0] = JBTerminalConfig({terminal: _terminal, accountingContextsToAccept: tokensToAccept});
103
+
104
+ // Fee project (#1) — needed so fees can be processed.
105
+ JBRulesetConfig[] memory feeRulesetConfig = new JBRulesetConfig[](1);
106
+ feeRulesetConfig[0].mustStartAtOrAfter = 0;
107
+ feeRulesetConfig[0].duration = 0;
108
+ feeRulesetConfig[0].weight = 0;
109
+ feeRulesetConfig[0].weightCutPercent = 0;
110
+ feeRulesetConfig[0].approvalHook = IJBRulesetApprovalHook(address(0));
111
+ feeRulesetConfig[0].metadata = JBRulesetMetadata({
112
+ reservedPercent: 0,
113
+ cashOutTaxRate: 0,
114
+ baseCurrency: uint32(uint160(JBConstants.NATIVE_TOKEN)),
115
+ pausePay: false,
116
+ pauseCreditTransfers: false,
117
+ allowOwnerMinting: false,
118
+ allowSetCustomToken: false,
119
+ allowTerminalMigration: false,
120
+ allowSetTerminals: false,
121
+ ownerMustSendPayouts: false,
122
+ allowSetController: false,
123
+ allowAddAccountingContext: true,
124
+ allowAddPriceFeed: false,
125
+ holdFees: false,
126
+ useTotalSurplusForCashOuts: false,
127
+ useDataHookForPay: false,
128
+ useDataHookForCashOut: false,
129
+ dataHook: address(0),
130
+ metadata: 0
131
+ });
132
+ feeRulesetConfig[0].splitGroups = new JBSplitGroup[](0);
133
+ feeRulesetConfig[0].fundAccessLimitGroups = new JBFundAccessLimitGroup[](0);
134
+
135
+ _controller.launchProjectFor({
136
+ owner: address(420),
137
+ projectUri: "fee",
138
+ rulesetConfigurations: feeRulesetConfig,
139
+ terminalConfigurations: terminalConfigs,
140
+ memo: ""
141
+ });
142
+
143
+ // Test project (#2).
144
+ _projectId = _controller.launchProjectFor({
145
+ owner: _projectOwner,
146
+ projectUri: "test",
147
+ rulesetConfigurations: rulesetConfig,
148
+ terminalConfigurations: terminalConfigs,
149
+ memo: ""
150
+ });
151
+
152
+ // Deploy ERC20 so we can track token balances precisely.
153
+ vm.prank(_projectOwner);
154
+ _controller.deployERC20For(_projectId, "Test", "TST", bytes32(0));
155
+ }
156
+
157
+ /// @notice Full lifecycle: pay -> payout (held fees) -> cashOut -> distribute reserves.
158
+ /// Verifies that all three features interact correctly and accounting remains consistent.
159
+ function test_holdFees_cashOut_reservedPercent_fullLifecycle() external {
160
+ // ── Step 1: Pay into the project ──
161
+ _terminal.pay{value: PAY_AMOUNT}({
162
+ projectId: _projectId,
163
+ amount: PAY_AMOUNT,
164
+ token: JBConstants.NATIVE_TOKEN,
165
+ beneficiary: _payer,
166
+ minReturnedTokens: 0,
167
+ memo: "",
168
+ metadata: new bytes(0)
169
+ });
170
+
171
+ // After payment: store balance = 10 ETH, payer gets 50% of tokens (rest reserved).
172
+ assertEq(
173
+ _store.balanceOf(address(_terminal), _projectId, JBConstants.NATIVE_TOKEN),
174
+ PAY_AMOUNT,
175
+ "Store balance should equal payment amount"
176
+ );
177
+
178
+ uint256 payerTokens = _tokens.totalBalanceOf(_payer, _projectId);
179
+ {
180
+ // weight=1000e18 tokens per 1 ETH, pay=10 ETH => 10000e18 total. 50% reserved => payer gets 5000e18.
181
+ uint256 expectedPayerTokens = uint256(WEIGHT) * uint256(PAY_AMOUNT)
182
+ * (JBConstants.MAX_RESERVED_PERCENT - 5000) / JBConstants.MAX_RESERVED_PERCENT / 1 ether;
183
+ assertEq(payerTokens, expectedPayerTokens, "Payer should have 50% of minted tokens");
184
+ }
185
+
186
+ assertEq(
187
+ _controller.pendingReservedTokenBalanceOf(_projectId),
188
+ payerTokens,
189
+ "Pending reserves should equal payer tokens (50/50)"
190
+ );
191
+ assertEq(address(_terminal).balance, PAY_AMOUNT, "Terminal ETH should equal payment");
192
+
193
+ // ── Step 2: Send payouts (triggers held fees) ──
194
+ _terminal.sendPayoutsOf({
195
+ projectId: _projectId,
196
+ amount: PAYOUT_LIMIT,
197
+ currency: uint32(uint160(JBConstants.NATIVE_TOKEN)),
198
+ token: JBConstants.NATIVE_TOKEN,
199
+ minTokensPaidOut: 0
200
+ });
201
+
202
+ {
203
+ uint256 feeOnPayout = JBFees.feeAmountFrom({amountBeforeFee: PAYOUT_LIMIT, feePercent: _terminal.FEE()});
204
+
205
+ assertEq(
206
+ _store.balanceOf(address(_terminal), _projectId, JBConstants.NATIVE_TOKEN),
207
+ PAY_AMOUNT - PAYOUT_LIMIT,
208
+ "Store balance should be reduced by payout limit"
209
+ );
210
+ assertEq(_projectOwner.balance, PAYOUT_LIMIT - feeOnPayout, "Owner should receive payout minus fee");
211
+ assertEq(
212
+ address(_terminal).balance,
213
+ PAY_AMOUNT - (PAYOUT_LIMIT - feeOnPayout),
214
+ "Terminal should hold remaining balance + held fee"
215
+ );
216
+
217
+ JBFee[] memory heldFees = _terminal.heldFeesOf(_projectId, JBConstants.NATIVE_TOKEN, 10);
218
+ assertEq(heldFees.length, 1, "Should have one held fee");
219
+ assertEq(heldFees[0].amount, PAYOUT_LIMIT, "Held fee should record the full payout amount");
220
+ }
221
+
222
+ // ── Step 3: Cash out with tax + pending reserves ──
223
+ {
224
+ uint256 cashOutCount = payerTokens / 2;
225
+ uint256 surplus = _store.balanceOf(address(_terminal), _projectId, JBConstants.NATIVE_TOKEN);
226
+ uint256 totalSupply = _controller.totalTokenSupplyWithReservedTokensOf(_projectId);
227
+
228
+ uint256 grossReclaim = JBCashOuts.cashOutFrom({
229
+ surplus: surplus, cashOutCount: cashOutCount, totalSupply: totalSupply, cashOutTaxRate: 5000
230
+ });
231
+ assertGt(grossReclaim, 0, "Gross reclaim should be positive");
232
+
233
+ // Cashout fees are NOT held — processed immediately (shouldHoldFees: false in _cashOutTokensOf).
234
+ uint256 expectedNetReclaim =
235
+ grossReclaim - JBFees.feeAmountFrom({amountBeforeFee: grossReclaim, feePercent: _terminal.FEE()});
236
+ uint256 payerBalanceBefore = _payer.balance;
237
+
238
+ vm.prank(_payer);
239
+ uint256 actualReclaim = _terminal.cashOutTokensOf({
240
+ holder: _payer,
241
+ projectId: _projectId,
242
+ cashOutCount: cashOutCount,
243
+ tokenToReclaim: JBConstants.NATIVE_TOKEN,
244
+ minTokensReclaimed: 0,
245
+ beneficiary: payable(_payer),
246
+ metadata: new bytes(0)
247
+ });
248
+
249
+ assertEq(actualReclaim, expectedNetReclaim, "Actual reclaim should match bonding curve minus fee");
250
+ assertEq(
251
+ _payer.balance - payerBalanceBefore,
252
+ expectedNetReclaim,
253
+ "Payer ETH balance increase should equal net reclaim"
254
+ );
255
+ assertEq(
256
+ _tokens.totalBalanceOf(_payer, _projectId),
257
+ payerTokens - cashOutCount,
258
+ "Payer tokens should decrease by cashOut count"
259
+ );
260
+ }
261
+
262
+ // ── Step 4: Distribute reserved tokens ──
263
+ assertGt(
264
+ _controller.pendingReservedTokenBalanceOf(_projectId), 0, "Should have pending reserves before distribution"
265
+ );
266
+ _controller.sendReservedTokensToSplitsOf(_projectId);
267
+ assertEq(
268
+ _controller.pendingReservedTokenBalanceOf(_projectId), 0, "Pending reserves should be 0 after distribution"
269
+ );
270
+
271
+ // ── Step 5: Verify accounting invariants ──
272
+ {
273
+ uint256 finalStoreBalance = _store.balanceOf(address(_terminal), _projectId, JBConstants.NATIVE_TOKEN);
274
+ assertGe(
275
+ address(_terminal).balance, finalStoreBalance, "Terminal ETH balance must be >= store recorded balance"
276
+ );
277
+
278
+ uint256 totalTokenSupply = _tokens.totalSupplyOf(_projectId);
279
+ assertGt(totalTokenSupply, 0, "Total token supply should be positive");
280
+ assertEq(
281
+ _controller.totalTokenSupplyWithReservedTokensOf(_projectId),
282
+ totalTokenSupply,
283
+ "After distributing reserves, total supply with/without reserves should match"
284
+ );
285
+
286
+ // Conservation check: terminal balance >= project balance + held fee value.
287
+ JBFee[] memory remainingHeldFees = _terminal.heldFeesOf(_projectId, JBConstants.NATIVE_TOKEN, 100);
288
+ uint256 totalHeldFeeValue;
289
+ for (uint256 i; i < remainingHeldFees.length; i++) {
290
+ totalHeldFeeValue += JBFees.feeAmountFrom({
291
+ amountBeforeFee: remainingHeldFees[i].amount, feePercent: _terminal.FEE()
292
+ });
293
+ }
294
+ assertGe(
295
+ address(_terminal).balance,
296
+ finalStoreBalance + totalHeldFeeValue,
297
+ "Terminal balance must cover project balance + held fee amounts"
298
+ );
299
+ }
300
+ }
301
+
302
+ /// @notice Verify that held fees don't distort the surplus used in cashout calculations.
303
+ /// The store's recorded balance (not the terminal's ETH balance) determines surplus.
304
+ function test_heldFees_dontInflateSurplus() external {
305
+ // Pay into the project.
306
+ _terminal.pay{value: PAY_AMOUNT}({
307
+ projectId: _projectId,
308
+ amount: PAY_AMOUNT,
309
+ token: JBConstants.NATIVE_TOKEN,
310
+ beneficiary: _payer,
311
+ minReturnedTokens: 0,
312
+ memo: "",
313
+ metadata: new bytes(0)
314
+ });
315
+
316
+ // Send payouts to trigger held fees.
317
+ _terminal.sendPayoutsOf({
318
+ projectId: _projectId,
319
+ amount: PAYOUT_LIMIT,
320
+ currency: uint32(uint160(JBConstants.NATIVE_TOKEN)),
321
+ token: JBConstants.NATIVE_TOKEN,
322
+ minTokensPaidOut: 0
323
+ });
324
+
325
+ // The store balance (surplus base) should NOT include the held fee amount.
326
+ uint256 storeBalance = _store.balanceOf(address(_terminal), _projectId, JBConstants.NATIVE_TOKEN);
327
+ assertEq(storeBalance, PAY_AMOUNT - PAYOUT_LIMIT, "Store balance should not include held fees");
328
+
329
+ // The terminal's actual ETH balance includes the held fee.
330
+ assertGt(address(_terminal).balance, storeBalance, "Terminal ETH should exceed store balance due to held fees");
331
+
332
+ // The difference should be accounted for by held fees + fee project balance.
333
+ uint256 feeProjectBalance = _store.balanceOf(address(_terminal), 1, JBConstants.NATIVE_TOKEN);
334
+ JBFee[] memory heldFees = _terminal.heldFeesOf(_projectId, JBConstants.NATIVE_TOKEN, 10);
335
+ uint256 heldFeeValue;
336
+ for (uint256 i; i < heldFees.length; i++) {
337
+ heldFeeValue += JBFees.feeAmountFrom({amountBeforeFee: heldFees[i].amount, feePercent: _terminal.FEE()});
338
+ }
339
+
340
+ assertEq(
341
+ address(_terminal).balance,
342
+ storeBalance + heldFeeValue + feeProjectBalance,
343
+ "Terminal balance = project balance + held fee value + fee project balance"
344
+ );
345
+ }
346
+
347
+ /// @notice Cash out with pending reserves and held fees — verify bonding curve uses correct supply.
348
+ function test_cashOut_usesCorrectTotalSupply_withPendingReservesAndHeldFees() external {
349
+ // Pay into the project.
350
+ _terminal.pay{value: PAY_AMOUNT}({
351
+ projectId: _projectId,
352
+ amount: PAY_AMOUNT,
353
+ token: JBConstants.NATIVE_TOKEN,
354
+ beneficiary: _payer,
355
+ minReturnedTokens: 0,
356
+ memo: "",
357
+ metadata: new bytes(0)
358
+ });
359
+
360
+ // Send payouts (creating held fees).
361
+ _terminal.sendPayoutsOf({
362
+ projectId: _projectId,
363
+ amount: PAYOUT_LIMIT,
364
+ currency: uint32(uint160(JBConstants.NATIVE_TOKEN)),
365
+ token: JBConstants.NATIVE_TOKEN,
366
+ minTokensPaidOut: 0
367
+ });
368
+
369
+ uint256 payerTokens = _tokens.totalBalanceOf(_payer, _projectId);
370
+ uint256 surplus = _store.balanceOf(address(_terminal), _projectId, JBConstants.NATIVE_TOKEN);
371
+
372
+ // Total supply WITH pending reserves (what the system uses for cashOut).
373
+ uint256 totalWithReserves = _controller.totalTokenSupplyWithReservedTokensOf(_projectId);
374
+ // Total supply WITHOUT pending reserves.
375
+ uint256 circulatingSupply = _tokens.totalSupplyOf(_projectId);
376
+
377
+ // Pending reserves should inflate total supply.
378
+ assertGt(totalWithReserves, circulatingSupply, "Total with reserves > circulating");
379
+
380
+ // Compute expected cashout with the inflated supply (what the system does).
381
+ uint256 reclaimWithReserves = JBCashOuts.cashOutFrom({
382
+ surplus: surplus, cashOutCount: payerTokens, totalSupply: totalWithReserves, cashOutTaxRate: 5000
383
+ });
384
+
385
+ // Compute hypothetical cashout without pending reserves.
386
+ uint256 reclaimWithoutReserves = JBCashOuts.cashOutFrom({
387
+ surplus: surplus, cashOutCount: payerTokens, totalSupply: circulatingSupply, cashOutTaxRate: 5000
388
+ });
389
+
390
+ // With pending reserves, the cashout value is lower (known behavior, H-4).
391
+ assertLt(reclaimWithReserves, reclaimWithoutReserves, "Pending reserves reduce cashout value (expected, H-4)");
392
+
393
+ // Actually perform the cashout and confirm it matches the with-reserves calculation (net of fee).
394
+ // cashOutTokensOf returns the NET reclaim after the 2.5% fee is deducted.
395
+ uint256 feeOnReclaim = JBFees.feeAmountFrom({amountBeforeFee: reclaimWithReserves, feePercent: _terminal.FEE()});
396
+ uint256 expectedNetReclaim = reclaimWithReserves - feeOnReclaim;
397
+
398
+ vm.prank(_payer);
399
+ uint256 actualReclaim = _terminal.cashOutTokensOf({
400
+ holder: _payer,
401
+ projectId: _projectId,
402
+ cashOutCount: payerTokens,
403
+ tokenToReclaim: JBConstants.NATIVE_TOKEN,
404
+ minTokensReclaimed: 0,
405
+ beneficiary: payable(_payer),
406
+ metadata: new bytes(0)
407
+ });
408
+
409
+ assertEq(
410
+ actualReclaim,
411
+ expectedNetReclaim,
412
+ "Actual cashout should match bonding curve with pending reserves (net of fee)"
413
+ );
414
+ }
415
+ }